AES。加密PowerShell中的字节数组

时间:2012-12-03 03:19:27

标签: algorithm powershell encryption aes encryption-symmetric

我需要使用AES加密方法在powershell脚本中加密字节数组([byte []])。我找到编码字符串的函数:

[Reflection.Assembly]::LoadWithPartialName("System.Security")

function Encrypt-String($String, $Passphrase, $salt="My Voice is my P455W0RD!",     $init="Yet another key", [switch]$arrayOutput)
{
   $r = new-Object System.Security.Cryptography.RijndaelManaged
   $pass = [Text.Encoding]::UTF8.GetBytes($Passphrase)
   $salt = [Text.Encoding]::UTF8.GetBytes($salt)

   $r.Key = (new-Object Security.Cryptography.PasswordDeriveBytes $pass, $salt, "SHA1", 5).GetBytes(32) #256/8
   $r.IV = (new-Object Security.Cryptography.SHA1Managed).ComputeHash( [Text.Encoding]::UTF8.GetBytes($init) )[0..15]

   $c = $r.CreateEncryptor()
   $ms = new-Object IO.MemoryStream
   $cs = new-Object Security.Cryptography.CryptoStream $ms,$c,"Write"
   $sw = new-Object IO.StreamWriter $cs
   $sw.Write($String)
   $sw.Close()
   $cs.Close()
   $ms.Close()
   $r.Clear()
   [byte[]]$result = $ms.ToArray()
   if($arrayOutput) {
  return $result
   } else {
      return [Convert]::ToBase64String($result)
   }
}

http://gallery.technet.microsoft.com/scriptcenter/PowerShell-Script-410ef9df

处阅读评论代码

帮助更改函数,使其编码字节数组而不是字符串

Ssory为我的英语。来自俄罗斯的问候:)

1 个答案:

答案 0 :(得分:0)

我这样做是我需要的。新代码:

[Reflection.Assembly]::LoadWithPartialName("System.Security")

 $String=$buff #ARRAY OF BYTES TO ENCODE
 $Passphrase="Pas"
  $salt="My Voice is my P455W0RD!"
  $init="Yet another key"

   $r = new-Object System.Security.Cryptography.AesManaged
   $pass = [Text.Encoding]::UTF8.GetBytes($Passphrase)
   $salt = [Text.Encoding]::UTF8.GetBytes($salt)

   $r.Key = (new-Object Security.Cryptography.PasswordDeriveBytes $pass, $salt, "SHA1", 5).GetBytes(32) #256/8
   $r.IV = (new-Object Security.Cryptography.SHA1Managed).ComputeHash( [Text.Encoding]::UTF8.GetBytes($init) )[0..15]
   $r.Padding="Zeros"

   $c = $r.CreateEncryptor()
   $ms = new-Object IO.MemoryStream
   $cs = new-Object Security.Cryptography.CryptoStream $ms,$c,"Write"
   $cs.Write($String, 0,$String.Length)
   $cs.Close()
   $ms.Close()
   $r.Clear()
   [byte[]]$Encrypted = $ms.ToArray()