I use AesCryptoServiceProvider in order to perform encryption and decryption using AES. Encryption seems to work, but decryption throws an exception saying "Padding is invalid and cannot be removed".
Here is my code:
Public Function AESEnc(ByVal plain As String, ByVal key As String, ByVal iv As String) As AesResult
Dim ciphertext As String
Dim k(31) As Byte
Dim v(15) As Byte
Dim ret As AesResult
Dim pBytes As Byte() = StrToByteArray(plain)
Dim cipher As New AesCryptoServiceProvider()
Dim enc As ICryptoTransform
Dim ms As New MemoryStream
Dim cs As CryptoStream
k = StrToByteArray(key)
v = HexStringByteArrayConverter.HexStringToBytes(iv)
cipher.Mode = CipherMode.CFB
cipher.Padding = PaddingMode.PKCS7
enc = cipher.CreateEncryptor(k, v)
cs = New CryptoStream(ms, enc, CryptoStreamMode.Write)
cs.Write(pBytes, 0, pBytes.Length)
cs.FlushFinalBlock()
cs.Close()
ciphertext = HexStringByteArrayConverter.BytesToHexString(ms.ToArray())
ret.data = ciphertext
ret.iv = v
ret.key = k
Return ret
End Function 'AESEnc
Public Function AESDec(ByVal ciphertext As String, ByVal key As String, ByVal iv As String) As AesResult
Dim plaintext As String
Dim k(31) As Byte
Dim v(15) As Byte
Dim ret As AesResult
Dim pBytes As Byte() = StrToByteArray(ciphertext)
Dim cipher As New AesCryptoServiceProvider()
Dim dec As ICryptoTransform
Dim ms As New MemoryStream
Dim cs As CryptoStream
k = StrToByteArray(key)
v = HexStringByteArrayConverter.HexStringToBytes(iv)
cipher.Mode = CipherMode.CFB
cipher.Padding = PaddingMode.PKCS7
dec = cipher.CreateDecryptor(k, v)
cs = New CryptoStream(ms, dec, CryptoStreamMode.Write)
cs.Write(pBytes, 0, pBytes.Length)
cs.FlushFinalBlock()
cs.Close()
plaintext = ByteArrayToString(ms.ToArray())
ret.data = plaintext
ret.iv = v
ret.key = k
Return ret
End Function 'AESDec