I keep getting this "The input data is not a complete block." error while decrypting. The function successfully encrypts plain text and puts the IV in a textbox. I am using the encrypted data and the IV from text to decrypt the original data but I keep getting the error. I have no idea where I have gone wrong. Heres my code
Imports System.IO 'Import file I/O tools
Imports System.Security.Cryptography 'Import encryption functionality
Imports System.Text 'Import text based processing tools`
Public Class Form1
Private Function AESEncryption(ByVal clearText As String, ByVal key As String) As String
Dim salt As String = tbpassword.Text.Insert(tbpassword.Text.Length - 1, "7?1!")
Dim Md5 As New MD5CryptoServiceProvider()
Dim Encryptionkey As Byte() = Md5.ComputeHash(Encoding.UTF8.GetBytes(key & salt))
Dim AES As New AesCryptoServiceProvider
AES.Key = Encryptionkey
AES.Mode = CipherMode.CBC
tbIV.Text = Convert.ToBase64String(AES.IV)
Dim datain() As Byte = Encoding.UTF8.GetBytes(clearText)
Dim memorystream As New MemoryStream(datain)
Dim cstream As New CryptoStream(memorystream, AES.CreateEncryptor, CryptoStreamMode.Write)
cstream.Write(datain, 0, datain.Length)
AES.Clear()
memorystream.Close()
Return Convert.ToBase64String(memorystream.ToArray())
End Function
Private Function AESdecryption(ByVal encrypteddata As String, ByVal key As String) As String
Dim salt As String = tbpassword.Text.Insert(tbpassword.Text.Length - 1, "7?1!")
Dim Md5 As New MD5CryptoServiceProvider()
Dim Encryptionkey As Byte() = Md5.ComputeHash(Encoding.UTF8.GetBytes(key & salt)) 'uses password and salt to create a hash byte array
Dim EncryptionIn() As Byte = Convert.FromBase64String(encrypteddata)
Dim AES As New AesCryptoServiceProvider
AES.Key = Encryptionkey
AES.Mode = CipherMode.CBC
AES.IV = Convert.FromBase64String(tbIV.Text)
Dim ms As New MemoryStream(EncryptionIn)
Dim cryptostream As New CryptoStream(ms, AES.CreateDecryptor, CryptoStreamMode.Read)
Dim decrypteddata() As Byte
ReDim decrypteddata(EncryptionIn.Length - 1)
cryptostream.Read(decrypteddata, 0, decrypteddata.Length)
AES.Clear()
ms.Close()
Return Convert.ToBase64String(ms.ToArray)
End Function
Private Sub btnencrypt_Click(sender As Object, e As EventArgs) Handles btnencrypt.Click
tbencrypteddata.Text = AESEncryption(tbuserdata.Text, tbpassword.Text)
End Sub
Private Sub btndecrypt_Click(sender As Object, e As EventArgs) Handles Button1.Click
tbdecrypteddata.Text = AESdecryption(tbencrypteddata.Text, tbpassword.Text)
End Sub
End Class