Saturday 14 November 2009

Protect-ByteArray.ps1

  1. <# 
  2. .SYNOPSIS 
  3.     This script encrpyts then decrypts a byte string 
  4. .DESCRIPTION 
  5.     This script uses System.Security to encrpyt a byte 
  6.     string, then decrypts it. 
  7. .NOTES 
  8.     File Name  : Protect-ByteArray.ps1 
  9.     Author     : Thomas Lee - tfl@psp.co.uk 
  10.     Requires   : PowerShell V2 
  11. .LINK 
  12.     This script posted to: 
  13.         http://www.pshscripts.blogspot.com 
  14.     MSDN Sample posted at: 
  15.         http://msdn.microsoft.com/en-us/library/system.security.cryptography.protectedmemory.aspx 
  16. .EXAMPLE 
  17.     PSH [C:\foo]: .Protect-ByteArray.ps1' 
  18.     Unencrpyted byte string: 
  19.     1 
  20.     2 
  21.     3 
  22.     4 
  23.     1 
  24.     2 
  25.     3 
  26.     4 
  27.     1 
  28.     2 
  29.     3 
  30.     4 
  31.     1 
  32.     2 
  33.     3 
  34.     6 
  35.     Encrpyted byte string: 
  36.     199 
  37.     52 
  38.     177 
  39.     169 
  40.     162 
  41.     117 
  42.     118 
  43.     127 
  44.     180 
  45.     16 
  46.     230 
  47.     70 
  48.     19 
  49.     89 
  50.     85 
  51.     168 
  52.     Unencrpyted byte string: 
  53.     1 
  54.     2 
  55.     3 
  56.     4 
  57.     1 
  58.     2 
  59.     3 
  60.     4 
  61.     1 
  62.     2 
  63.     3 
  64.     4 
  65.     1 
  66.     2 
  67.     3 
  68.     6 
  69. #> 
  70.    
  71. ## 
  72. # Start of script 
  73. ## 
  74.   
  75. # Load System.Security  
  76. [void] [Reflection.Assembly]::LoadWithPartialName("System.Security") 
  77.   
  78. # Create and display a byte string 
  79. [byte[]] $Secret =  1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3,6 
  80. "Unencrpyted byte string:" 
  81. $Secret 
  82.   
  83. # now encrypt it and display the encrpyted string 
  84. [System.Security.Cryptography.ProtectedMemory]::Protect($Secret,[System.Security.Cryptography.MemoryProtectionScope]::SameLogon) 
  85. "Encrpyted byte string:" 
  86. $Secret 
  87.   
  88. # Now decrypt it and re-display it - it's the same byte array we started with 
  89. [System.Security.Cryptography.ProtectedMemory]::UnProtect($Secret,[System.Security.Cryptography.MemoryProtectionScope]::SameLogon) 
  90. "Unencrpyted byte string:" 
  91. $Secret 
  92. #End of Script