更改函数以使用SHA256散列而不是SHA1散列

时间:2016-08-12 05:56:19

标签: .net powershell sha1 sha256 sha2

有人可以帮助我解决以下问题 我有以下功能,工作正常

function Decrypt-String($Encrypted, $Passphrase, $salt, $init) 
{ 
    if($Encrypted -is [string]){ 
        $Encrypted = [Convert]::FromBase64String($Encrypted) 
       } 

    $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] 

    $d = $r.CreateDecryptor() 
    $ms = new-Object IO.MemoryStream @(,$Encrypted) 
    $cs = new-Object Security.Cryptography.CryptoStream $ms,$d,"Read" 
    $sr = new-Object IO.StreamReader $cs 
    Write-Output $sr.ReadToEnd() 
    $sr.Close() 
    $cs.Close() 
    $ms.Close() 
    $r.Clear() 
}

代码中有两个位置引用SHA1

我想切换到SHA256,虽然上面提到的.NET都支持SHA256,但它会抛出以下错误,我将单个从SHA1更改为SHA256

Exception calling "ReadToEnd" with "0" argument(s): "Padding is invalid and cannot be removed."
At J:\UTemp\063146ee-175d-4a33-b485-7c6dd0e309f6.ps1:28 char:5
+     Write-Output $sr.ReadToEnd()
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : CryptographicException

Exception calling "Close" with "0" argument(s): "Padding is invalid and cannot be removed."
At J:\UTemp\063146ee-175d-4a33-b485-7c6dd0e309f6.ps1:29 char:5
+     $sr.Close()
+     ~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : CryptographicException

欢迎任何帮助 欧尼

0 个答案:

没有答案