Monday 8 October 2012

Use SHA1 Crypto provider to create a Hash of a pass key to tripledes encrypt/decrypt a string:

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

#>

1 comment: