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. ) 
  42. $inBlock = [System.Text.UnicodeEncoding]::Unicode.getbytes($instring) 
  43. $xfrm = $symAlg.CreateEncryptor() 
  44. $outBlock = $xfrm.TransformFinalBlock($inBlock, 0, $inBlock.Length); 
  45. return $outBlock; 
  46. } 
  47.   
  48. function DecryptBytes { 
  49. param ($SymAlg,  
  50. $inBytes 
  51. ) 
  52. $xfrm = $symAlg.CreateDecryptor(); 
  53. $outBlock = $xfrm.TransformFinalBlock($inBytes, 0, $inBytes.Length) 
  54. return [System.Text.UnicodeEncoding]::Unicode.GetString($outBlock) 
  55. } 
  56.  
  57. # main script 
  58. $Quote = "Things may come to those who wait, but only the " + 
  59.          "things left by those who hustle. -- Abraham Lincoln" 
  60. "Quote:";$Quote;"" 
  61.   
  62. # Generate CSP, Key and IV 
  63. $AesCSP = New-Object System.Security.Cryptography.AesCryptoServiceProvider 
  64. $AesCSP.GenerateKey() 
  65. $AesCSP.GenerateIV() 
  66.  
  67. # Encrypt quote 
  68. $EncQuote = EncryptString $aesCSP $quote 
  69. "Encrypted Quote:" 
  70. [System.Convert]::ToBase64String($encQuote) 
  71. "" 
  72.   
  73. # Now Decrypt  
  74. "Decrypted Quote:" 
  75. DecryptBytes $AesCSP $EncQuote 

No comments: