我正在尝试使用PowerShell中的Aes进行简单的加密/解密,但在尝试解密输出时我一直遇到异常。
我得到例外:
使用“0”参数调用“ReadToEnd”的异常:“填充是 无效且无法删除。“
有什么想法吗?
Function Aes-Encrypt( $plainTextBytes ){
$key = "vqMcLYelBxefzIAMpO9Q/Q=="
$plainText = [System.Text.Encoding]::UTF8.GetBytes($plainTextBytes)
#Use the AES cipher and represent it as an object.
$AES = New-Object "System.Security.Cryptography.AesManaged"
$AES.Mode = [System.Security.Cryptography.CipherMode]::CBC
$AES.Padding = [System.Security.Cryptography.PaddingMode]::PKCS7
$AES.BlockSize = 128
$AES.KeySize = 128
$IV = $AES.IV
#$AES.Key = $key
# Creates a MemoryStream to do the encryption in
$ms = new-Object IO.MemoryStream
# Creates the new Cryptology Stream --> Outputs to $MS or Memory Stream
$cs = new-Object Security.Cryptography.CryptoStream $ms,$AES.CreateEncryptor(),"Write"
#Writes the string in the Cryptology Stream
$cs.Write($IV, 0, 16)
$cs.Write($plainText, 0, $plainText.Length);
$cs.FlushFinalBlock();
# Stops the Cryptology Stream
$cs.Close()
# Stops writing to Memory
$ms.Close()
# Clears the IV and HASH from memory to prevent memory read attacks
$cs.Clear()
# Takes the MemoryStream and puts it to an array
[byte[]]$rmesult = $ms.ToArray()
# return $ms.ToArray()
# Converts the array from Base 64 to a string and returns
return [Convert]::ToBase64String($rmesult)
}
Function Aes-Decrypt( $DecryptData ){
$key = "vqMcLYelBxefzIAMpO9Q/Q=="
#$plainText = [System.Text.Encoding]::UTF8.GetBytes($plainTextBytes)
# Create a COM Object for RijndaelManaged Cryptography
#$r = new-Object System.Security.Cryptography.RijndaelManaged
#Use the AES cipher and represent it as an object.
$AES = New-Object "System.Security.Cryptography.AesManaged"
$AES.Mode = [System.Security.Cryptography.CipherMode]::CBC
$AES.Padding = [System.Security.Cryptography.PaddingMode]::PKCS7
$AES.BlockSize = 128
$AES.KeySize = 128
$IV = $AES.IV
#$AES.Key = $key
$cipherTextBytes = [Convert]::FromBase64String($DecryptData)
# Creates a MemoryStream to do the encryption in
$ms = new-Object IO.MemoryStream @(,$cipherTextBytes)
# Creates the new Cryptology Stream --> Outputs to $MS or Memory Stream
$cs = new-Object Security.Cryptography.CryptoStream $ms,$AES.CreateDecryptor(),"Read"
# Read the new decrypted stream
$sr = new-Object IO.StreamReader $cs
# Return from the function the stream
Write-Output $sr.ReadToEnd()
# Stops the stream
$sr.Close()
# Stops the crypology stream
$cs.Close()
# Stops writing to Memory
$ms.Close()
$cs.Clear()
# Takes the MemoryStream and puts it to an array
return $ms.ToArray()
}
答案 0 :(得分:0)
消息:
“填充无效,无法删除。”
是加密无效的一般症状,如果您不在加密和加密时使用相同的密钥和IV,则可能会出现这种情况。解密,或者加密消息是否以某种方式被更改。
在您的代码中,您似乎没有设置密钥,并且您不会生成随机IV。此外,您似乎在加密流中加密IV,这不会产生您正常期望的效果。
您需要生成一个随机IV并将其与您的加密数据一起以未加密的形式传递(它不需要保密)。然后,您的解密器需要在开始解密之前读取IV并使用它初始化AES密码。