Wednesday, 11 August 2010

Get-EncryptedAesString.ps1

  1. <# 
  2. .SYNOPSIS 
  3.     This script encrypts then decrypts a string using AES 
  4. .DESCRIPTION 
  5.     This script re-implements an MSDN sample that first  
  6.     encrypts a string then decrypts it. The crypto is done 
  7.     using AES. Running this script multiple times will result 
  8.     in differently encrypted quotes since a new key/IV is  
  9.     generated each time you run the script. 
  10. .NOTES 
  11.     File Name  : Get-AesEnctyptedString.ps1 
  12.     Author     : Thomas Lee - tfl@psp.co.uk 
  13.     Requires   : PowerShell Version 2.0 
  14. .LINK 
  15.     This script posted to: 
  16.         http://pshscripts.blogspot.com/2010/08/get-encryptedaesstringps1.html 
  17.     MSDN Sample posted at: 
  18.         http://msdn.microsoft.com/en-us/library/09d0kyb3.aspx  
  19. .EXAMPLE 
  20.     PSH [C:\foo]: .\Get-AesEncryptedString.ps1 
  21.     Quote: 
  22.     Things may come to those who wait, but only the things left by those who hustle. -- Abraham Lincoln 
  23.   
  24.     Encrypted Quote: 
  25.     zp4gD/Mmu01Msr3V8d94Kvwut4ClaW+f1HyohT+QjpFN5FVNhyLcQIgia4iD2TcsK/SpLcm5cOi1/KM+d9ENeU2Lkn8fOZHpMnklUrABGDoM1BRQDfWNcVbMIOA4IUY 
  26.     zLoJ5huHKhnyPA2fobGouW33HOpONI0zR3KS4RdtD3M3QQsqHW2+QOkE4/Ls/5gCSbcTuP2FDkk3J9b+1XgqzJZx0jZIBl+moUcqA33xQdu5bGhwg1E8sk2oEU8AQyy 
  27.     XcRrS/h8vTLve8c0Tpj4f2Vg== 
  28.   
  29.     Decrypted Quote: 
  30.     Things may come to those who wait, but only the things left by those who hustle. -- Abraham Lincoln 
  31. #> 
  32.  
  33.  
  34. # Best Practice! 
  35. Set-StrictMode  -version 2 
  36.   
  37. # Two helper functions 
  38. function EncryptString{ 
  39. param( $SymAlg,  
  40.       [string] $inString 
  41. $inBlock = [System.Text.UnicodeEncoding]::Unicode.getbytes($instring
  42. $xfrm = $symAlg.CreateEncryptor() 
  43. $outBlock = $xfrm.TransformFinalBlock($inBlock, 0, $inBlock.Length); 
  44. return $outBlock
  45.   
  46. function DecryptBytes { 
  47. param ($SymAlg,  
  48. $inBytes 
  49. $xfrm = $symAlg.CreateDecryptor(); 
  50. $outBlock = $xfrm.TransformFinalBlock($inBytes, 0, $inBytes.Length) 
  51. return [System.Text.UnicodeEncoding]::Unicode.GetString($outBlock
  52.  
  53. # main script 
  54. $Quote = "Things may come to those who wait, but only the "
  55.          "things left by those who hustle. -- Abraham Lincoln" 
  56. "Quote:";$Quote;"" 
  57.   
  58. # Generate CSP, Key and IV 
  59. $AesCSP = New-Object System.Security.Cryptography.AesCryptoServiceProvider 
  60. $AesCSP.GenerateKey() 
  61. $AesCSP.GenerateIV() 
  62.  
  63. # Encrypt quote 
  64. $EncQuote = EncryptString $aesCSP $quote 
  65. "Encrypted Quote:" 
  66. [System.Convert]::ToBase64String($encQuote
  67. "" 
  68.   
  69. # Now Decrypt  
  70. "Decrypted Quote:" 
  71. DecryptBytes $AesCSP $EncQuote 

No comments: