Post by burt0010 on Aug 16, 2007 22:56:24 GMT -5
I'm using the following code which works great to encrypt/decrypt strings, but I get an "Invalid Padding" runtime error when I try to decrypt using a different password. I'm trying to harden the code for production. What types of exceptions should I be looking for?
Thanks,
--jason
----------------------------------------------------------------------------------
Thanks,
--jason
----------------------------------------------------------------------------------
Option Explicit
Const SALT = "1234567890123456789012345678901234567890"
Public Function Encrypt(Message As String, Password As String)
Dim Alg As SymmetricAlgorithm
Set Alg = GetCryptoProvider(Password)
Encrypt = Convert.ToBase64String(EncryptData(Message, Alg))
Set Alg = Nothing
End Function
Public Function Decrypt(Message As String, Password As String)
Dim Alg As SymmetricAlgorithm
Set Alg = GetCryptoProvider(Password)
Decrypt = DecryptData(Convert.FromBase64String(Message), Alg)
Set Alg = Nothing
End Function
Private Function GetCryptoProvider(ByVal Password As String) As SymmetricAlgorithm
Dim SecureKey As Rfc2898DeriveBytes
Dim Alg As New RijndaelManaged
Dim Bytes() As Byte
Bytes = StrConv(SALT, vbFromUnicode)
Set SecureKey = Cor.NewRfc2898DeriveBytes(Password, Bytes)
Alg.KeySize = 256
Alg.BlockSize = 128
Alg.Key = SecureKey.GetBytes(32)
Alg.IV = SecureKey.GetBytes(16)
Alg.Padding = PKCS7
Set GetCryptoProvider = Alg
Set SecureKey = Nothing
End Function
' Encrypt the string.
Private Function EncryptData(ByVal PlainText As String, ByVal Alg As SymmetricAlgorithm) As Byte()
Dim Buffer() As Byte
Buffer = StrConv(PlainText, vbFromUnicode)
Dim Encryptor As ICryptoTransform
Set Encryptor = Alg.CreateEncryptor
EncryptData = Encryptor.TransformFinalBlock(Buffer, 0, cArray.GetLength(Buffer))
Set Encryptor = Nothing
End Function
' Decrypt the byte array.
Public Function DecryptData(ByRef CypherText() As Byte, ByVal Alg As SymmetricAlgorithm) As String
Dim Decryptor As ICryptoTransform
Set Decryptor = Alg.CreateDecryptor
Dim Buffer() As Byte
Buffer = Decryptor.TransformFinalBlock(CypherText, 0, cArray.GetLength(CypherText))
DecryptData = StrConv(Buffer, vbUnicode)
Set Decryptor = Nothing
End Function