Using AesCryptoServiceProvider in VB.NET
- by Collegeman
My problem is actually a bit more complicated than just how to use AES in VB.NET, since what I'm really trying to do is use AES in VB.NET from within a Java application across JACOB. But for now, what I need to focus on is the AES implementation itself.
Here's my encryption code
Public Function EncryptAES(ByVal toEncrypt As String, ByVal key As String) As Byte()
Dim keyArray = Convert.FromBase64String(key)
Dim toEncryptArray = Encoding.Unicode.GetBytes(toEncrypt)
Dim aes = New AesCryptoServiceProvider
aes.Key = keyArray
aes.Mode = CipherMode.ECB
aes.Padding = PaddingMode.ISO10126
Dim encryptor = aes.CreateEncryptor()
Dim encrypted = encryptor.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length)
aes.Clear()
Return encrypted
End Function
Once back in the Java code, I turn the byte array into a hexadecimal String.
Now, to reverse the process, here's my decryption code
Public Function DecryptAES(ByVal toDecrypt As String, ByVal key As String) As Byte()
Dim keyArray = Convert.FromBase64String(key)
Dim toDecryptArray = Convert.FromBase64String(toDecrypt)
Dim aes = New AesCryptoServiceProvider
aes.Key = keyArray
aes.Mode = CipherMode.ECB
aes.Padding = PaddingMode.ISO10126
Dim decryptor = aes.CreateDecryptor()
Dim decrypted = decryptor.TransformFinalBlock(toDecryptArray, 0, toDecryptArray.Length)
aes.Clear()
Return decrypted
End Function
When I run the decryption code, I get the following error message
Padding is invalid and cannot be removed.