I have an issue when trying to switch between 256 and 128 bit encryption with my code. If I keep it at 256bit, it works fine, but when I try it again using a 128 bit key, I get an error of "Padding is invalid and cannot be removed." Any help is much appreciated. I am no pro at encryption. The error is thrown when the "DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length)" part of the AES_Decrypt function is called.
Public Shared Function GenerateEncryptionKey(Optional ByVal keySizeIndex As Integer = 1) As Byte()
'Generate a Key.
Dim rm As RijndaelManaged = New RijndaelManaged()
Select Case keySizeIndex
Case 0
rm.KeySize = 128
Case 1
rm.KeySize = 256
Case Else
rm.KeySize = 256
End Select
rm.GenerateKey()
Return rm.Key
End Function
Public Shared Function AES_Encrypt(ByVal input As String, ByVal pass As Byte()) As String
Dim AES As New RijndaelManaged
Dim encrypted As String = ""
Dim hash As Byte()
Dim byteLength As Integer
Try
byteLength = pass.Length
ReDim hash(byteLength - 1)
Array.Copy(pass, 0, hash, 0, 16)
If (byteLength > 16) Then
Array.Copy(pass, 0, hash, 15, 16)
End If
AES.Key = hash
AES.Mode = Security.Cryptography.CipherMode.ECB
Dim DESEncrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateEncryptor
Dim Buffer As Byte() = System.Text.Encoding.Unicode.GetBytes(input)
'Dim Buffer As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(input)
Dim testBuffer As Byte() = DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length)
encrypted = Convert.ToBase64String(DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
Catch ex As Exception
encrypted = ""
End Try
Return encrypted
End Function
Public Shared Function AES_Decrypt(ByVal input As String, ByVal pass As Byte()) As String
Dim AES As New RijndaelManaged
Dim decrypted As String = ""
Dim hash As Byte()
Dim byteLength As Integer
Try
byteLength = pass.Length
ReDim hash(byteLength - 1)
Array.Copy(pass, 0, hash, 0, 16)
If (byteLength > 16) Then
Array.Copy(pass, 0, hash, 15, 16)
End If
AES.Key = hash
AES.Mode = Security.Cryptography.CipherMode.ECB
Dim DESDecrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateDecryptor
Dim Buffer As Byte() = Convert.FromBase64String(input)
Dim testBuffer As Byte() = DESDecrypter.TransformFinalBlock(Buffer, 0, Buffer.Length)
decrypted = System.Text.Encoding.Unicode.GetString(DESDecrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
'decrypted = System.Text.ASCIIEncoding.ASCII.GetString(DESDecrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
Catch ex As Exception
decrypted = ""
End Try
Return decrypted
End Function