I get the Cryptographic Exception Padding is invalid and cannot be removed
when trying to decrypt data. There are many questions on the net and on StackOverflow about this error, but I could not find the solution. More particularly, setting the Padding
to None
or explicitly defining the BlockSize
did not seem to help.
I have a sub that encrypts and decrypts a little XML
file placed on my hard drive. As parameters, the sub receives the location of the file and whether it should encrypt or decrypt. Here is the code:
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
The error occurs at the line outStreamEncrypted.FlushFinalBlock()
. I noted that the length of data
was different during encryption (156) and decryption (160).