I use the following two methods to encrypt and decrypt strings:
'Encrypts string. Returns encrypted byte array.
Public Function Encrypt(ByVal str As String) As Byte()
Dim inputInBytes() As Byte = Encoding.Unicode.GetBytes(str)
Dim laesProvider As New AesCryptoServiceProvider()
laesProvider.Key = _key
laesProvider.Mode = CipherMode.CBC
laesProvider.IV = _IV
laesProvider.Padding = PaddingMode.PKCS7
Dim lencryptor As ICryptoTransform = laesProvider.CreateEncryptor
Dim encryptedStream As New MemorySt开发者_如何学JAVAream
Dim cryptStream As CryptoStream = New CryptoStream(encryptedStream, lencryptor, CryptoStreamMode.Write)
cryptStream.Write(inputInBytes, 0, inputInBytes.Length)
cryptStream.FlushFinalBlock()
encryptedStream.Position = 0
Dim result(encryptedStream.Length - 1) As Byte
encryptedStream.Read(result, 0, encryptedStream.Length)
cryptStream.Close()
Return result
End Function
'Decrypts bytearray. Returns string.
Public Function DecryptToStr(ByVal inputInBytes() As Byte) As String
Dim laesProvider As New AesCryptoServiceProvider()
laesProvider.Key = _key
laesProvider.Mode = CipherMode.CBC
laesProvider.IV = _IV
laesProvider.Padding = PaddingMode.PKCS7
Dim ldecryptor As ICryptoTransform = laesProvider.CreateDecryptor
' Provide a memory stream to decrypt information into
Dim decryptedStream As MemoryStream = New MemoryStream()
Dim cryptStream As CryptoStream = New CryptoStream(decryptedStream, ldecryptor, CryptoStreamMode.Write)
cryptStream.Write(inputInBytes, 0, inputInBytes.Length)
cryptStream.FlushFinalBlock() '#### This is where the exception is thrown ####
decryptedStream.Position = 0
' Read the memory stream and convert it back into a string
Dim result(decryptedStream.Length - 1) As Byte
decryptedStream.Read(result, 0, decryptedStream.Length)
cryptStream.Close()
Return Encoding.Unicode.GetString(result)
End Function
The error occurs when attempting to decrypt certain length strings. When the string is a social security # (11 chars including dashes) then is throws "The input data is not a complete block" CryptographicException. If I pass in for example a string that is exactly 8 characters long, then everything works as expected. I thought that the PKCS7 padding would take care of the various lengths. I'm sure that I'm missing something simple, but after hours of googling, the answer eludes me.
The issue wasn't in the encryption method, it was in the length of the varbinary set in the database where it was being stored. So the encrypted data was being truncated.
精彩评论