1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | param( [parameter(Mandatory = $true , HelpMessage = "Action type: e.g. Encrypt(E)/Decrypt(D)" )] [string] $Action , [parameter(Mandatory = $true , HelpMessage = "Pass Key should be the same as used to encrypt if decrypting" )] [string] $passKey , [parameter(Mandatory = $true , HelpMessage = "String to be encrypted or decrypted" )] [string] $message ) [System.Reflection.Assembly]::LoadWithPartialName( 'System.Security.Cryptography' ) [System.Reflection.Assembly]::LoadWithPartialName( 'System.Collections.Generic' ) [System.Reflection.Assembly]::LoadWithPartialName( 'System.Text' ) $HashProvider = New-Object System.Security.Cryptography.SHA1CryptoServiceProvider $TDESAlgorithm = New-Object System.Security.Cryptography.TripleDESCryptoServiceProvider [Byte[]] $TDESKey = $HashProvider .ComputeHash([System.Text.UTF8Encoding]::UTF8.GetBytes( $passKey )); $keyByte = New-Object byte[] 24 $TDESKey .CopyTo( $keyByte , 0); $TDESAlgorithm .Key = $keyByte $TDESAlgorithm .Mode = [System.Security.Cryptography.CipherMode]::ECB $TDESAlgorithm .Padding = [System.Security.Cryptography.PaddingMode]::PKCS7 switch -regex ( $Action .toLower()){ "d(ecrypt)?" { try{ [Byte[]] $DataToDecrypt = [convert]::FromBase64String( $Message ) $Decryptor = $TDESAlgorithm .CreateDecryptor() $Results = $Decryptor .TransformFinalBlock( $DataToDecrypt , 0, $DataToDecrypt .Length) }finally{ $TDESAlgorithm . Clear () $HashProvider . Clear () } return [System.Text.UTF8Encoding]::UTF8.GetString( $Results ) } "e(ncrypt)?" { [Byte[]] $DataToEncrypt = [System.Text.UTF8Encoding]::UTF8.GetBytes( $Message ) try{ $Encryptor = $TDESAlgorithm .CreateEncryptor(); $Results = $Encryptor .TransformFinalBlock( $DataToEncrypt , 0, $DataToEncrypt .Length); }finally{ $TDESAlgorithm . Clear (); $HashProvider . Clear (); } return [Convert]::ToBase64String( $Results ) } } < # .SYNOPSIS Encrypt or Decrypt strings with a pass key .DESCRIPTION Uses SHA1 Crypto provider to create a Hash of a pass key to tripledes encrypt/decrypt a string EDIT HISTORY : 08/10/2012 v1.0 Initial Release .PARAMETER Action Choose to Encrypt (E) or Decrypt (D) .PARAMETER passKey Pass key to be used to encrypt or decrypt a string .PARAMETER message String to be encrypted or decrypted .INPUTS None. .OUTPUTS Returns string .EXAMPLE PS > .\SHA1Crypt.ps1 -Action e -message testmessage -passKey thisismykey1 .EXAMPLE PS > .\SHA1Crypt.ps1 -Action Decrypt -message "IZTkBEuz6JbWvBlNQaN2wA==" -passKey thisismykey1 #> |
Monday, 8 October 2012
Use SHA1 Crypto provider to create a Hash of a pass key to tripledes encrypt/decrypt a string:
Subscribe to:
Post Comments (Atom)
Nice!!!
ReplyDelete