Padding is invalid and cannot be removed
尝试解密数据时出现加密异常。网上和 StackOverflow 上有很多关于这个错误的问题,但我找不到解决方案。更具体地说,将 设置Padding
为None
或明确定义BlockSize
似乎没有帮助。
我有一个 sub 可以加密和解密XML
放在我硬盘上的一个小文件。作为参数,sub 接收文件的位置以及是否应该加密或解密。这是代码:
Private Sub LicenceEncryptOrDecrypt(LizenzDatei As String, EncryptOrDecrypt As String)
Dim Rijndael As RijndaelManaged = New RijndaelManaged
Dim passPhrase As String = "SuperPassword"
Dim hashAlgorithm As String = "SHA1"
Dim passwordIterations As Integer = 3
Dim keySize As Integer = 128
Dim initVector As String = "16charLongString"
Rijndael.IV = Encoding.ASCII.GetBytes(initVector)
Dim saltValue As String = "DoYouWantSomeSalt"
Dim saltValueBytes As Byte() = Encoding.ASCII.GetBytes(saltValue)
Dim password As Rfc2898DeriveBytes = New Rfc2898DeriveBytes(passPhrase, saltValueBytes)
Rijndael.Key = password.GetBytes(keySize / 8)
Rijndael.Padding = PaddingMode.None
Dim transform As ICryptoTransform
Dim tempFile As String
Select Case EncryptOrDecrypt
Case "Encrypt"
transform = Rijndael.CreateEncryptor(Rijndael.Key, Rijndael.IV)
tempFile = LizenzDatei + ".enc"
Case "Decrypt"
transform = Rijndael.CreateDecryptor(Rijndael.Key, Rijndael.IV)
tempFile = LizenzDatei + ".dec"
Case Else
Debug.Print(">< EncryptOrDecrypt: Falshes parameter. Ende Sub.")
Success = False
End Select
Using inFS As FileStream = New FileStream(LizenzDatei, FileMode.Open)
Dim data() As Byte = New Byte(inFS.Length - 1) {}
Using outFS As FileStream = New FileStream(tempFile, FileMode.Create)
Using outStreamEncrypted As CryptoStream = New CryptoStream(outFS, transform, CryptoStreamMode.Write)
outStreamEncrypted.Write(data, 0, data.Length)
outStreamEncrypted.FlushFinalBlock()
outStreamEncrypted.Close()
End Using
outFS.Close()
End Using
inFS.Close()
End Using
File.Delete(LizenzDatei)
File.Move(tempFile, LizenzDatei)
End Sub
错误发生在该行outStreamEncrypted.FlushFinalBlock()
。我注意到data
在加密(156)和解密(160)期间的长度是不同的。