I have implemented the methods in this answer to encrypt and decrypt a string
This appears to be encrypt and decrypt fine for most strings until the string has two or more spaces.
I.e.
- 'Buzz' - encrypt / decrypt fine (Buffer /Length = 16)
- 'Buzz Aldrin' - encrypt / decrypt fine (Buffer /Length = 16)
- 'Buzz Aldrin Astronaut' - encrypt fine / decrypt error (Buffer /Length = 31)
System.Security.Cryptography.CryptographicException: 'Length of the data to decrypt is invalid.'
Public Shared Function AES_Decrypt(ByVal ciphertext As String, ByVal key As String) As String
Dim AES As New System.Security.Cryptography.RijndaelManaged
Dim SHA256 As New System.Security.Cryptography.SHA256Cng
Dim plaintext As String = ""
Dim iv As String = ""
Try
Dim ivct = ciphertext.Split(CChar("="))
iv = ivct(0) & "=="
ciphertext = ivct(2) & "=="
AES.Key = SHA256.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(key))
AES.IV = Convert.FromBase64String(iv)
AES.Mode = Security.Cryptography.CipherMode.CBC
Dim DESDecrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateDecryptor
Dim Buffer As Byte() = Convert.FromBase64String(ciphertext)
Exception ----> plaintext = System.Text.ASCIIEncoding.ASCII.GetString(DESDecrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
Return plaintext
Catch ex As system.Exception
Return ex.Message
End Try
End Function
Any ideas what I am doing wrong or how I might correct it?
Example Update
Try
Dim s1, s2, s3 As String
s1 = Crypto.AES_Encrypt("Buzz", "Password")
s2 = Crypto.AES_Encrypt("Buzz Aldrin", "Password")
s3 = Crypto.AES_Encrypt("Buzz Aldrin Astronaut", "Password")
Debug.Print("Buzz : " & s1 & " : " & Crypto.AES_Decrypt(s1, "Password"))
Debug.Print("Buzz Aldrin : " & s2 & " : " & Crypto.AES_Decrypt(s2, "Password"))
Debug.Print("Buzz Aldrin Astronaut : " & s3 & " : " & Crypto.AES_Decrypt(s3, "Password"))
Catch ex As System.Exception
Debug.Print(ex.Message.ToString())
End Try
Debug.Print Output
Buzz : aTBh1U0OFqW7+266LiC7Vg==GC6bUY5pK10L2KgQzpAtgg== : Buzz
Buzz Aldrin : 80fmD0z57R8jmmCkKhCsXg==dixi7bqheBzKhXcT1UEpWQ== : Buzz Aldrin
Exception thrown: 'System.Security.Cryptography.CryptographicException' in mscorlib.dll
Length of the data to decrypt is invalid.