错误填充无效,无法删除

时间:2013-03-25 14:21:11

标签: vb.net encryption cryptography rijndaelmanaged

我在尝试解密数据时遇到了加密异常Padding is invalid and cannot be removed。网上和StackOverflow上有很多关于这个错误的问题,但我找不到解决方案。更具体地说,将Padding设置为None或明确定义BlockSize似乎没有帮助。

我有一个子文件加密和解密放在我硬盘上的一个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)期间是不同的。

1 个答案:

答案 0 :(得分: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)

解决了我的问题。

谢谢大家!