1

Padding is invalid and cannot be removed尝试解密数据时出现加密异常。网上和 StackOverflow 上有很多关于这个错误的问题,但我找不到解决方案。更具体地说,将 设置PaddingNone或明确定义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)期间的长度是不同的。

4

1 回答 1

0

根据评论和问题Rijndael Decryption error-Length of the data to decrypt is invalid,我意识到我的错误来自输入FileStream。输入文件实际上从未被读取过。

更换线路

Using inFS As FileStream = New FileStream(LizenzDatei, FileMode.Open)
Dim data() As Byte = New Byte(inFS.Length - 1) {}

经过

Dim data() As Byte = System.IO.File.ReadAllBytes(LizenzDatei)

解决了我的问题。

谢谢大家!

于 2013-03-26T08:57:36.137 回答