I have a password that I'm encrypting using openssl AES-256-CBC
in php that I'm trying to decrypt in VB
. I'm having problems with an IV generated by the openssl_random_pseudo_bytes()
php function. If I just use a random IV string instead of calling openssl_random_pseudo_bytes()
which returns a string of bytes in php, my VB code returns the correct decrypted password. Any suggestions would be greatly appreciated.
I have the following php function that encrypts a password:
function f_infr_encrypt_value($password, $key) {
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('AES-256-CBC'));
return trim(
base64_encode(
openssl_encrypt($value, "AES-256-CBC", $key, 0, $iv) . '::' . $iv));
}
I have the following VB code that attempts to decrypt the password created by the php function above
Private Function DecryptPassword(encryptedPassword As String, key As String) As String
Try
'Decode password from base 64
Dim base64Decoded As String
Dim data() As Byte
data = System.Convert.FromBase64String(encryptedPassword)
base64Decoded = System.Text.ASCIIEncoding.ASCII.GetString(data)
'Separating the password from the IV. Delimeter is "::"
Dim ivct = base64Decoded.Split({"::"}, StringSplitOptions.None)
'baseEncodedPassword is the password that is encrypted using AES-256-CBC
Dim baseEncodedPassword As String
baseEncodedPassword = ivct(0)
Dim iv As String = ivct(1)
Dim sEncryptedString As String = baseEncodedPassword
Dim myRijndael As New RijndaelManaged
myRijndael.Padding = PaddingMode.Zeros
myRijndael.Mode = CipherMode.CBC
myRijndael.KeySize = 256
myRijndael.BlockSize = 128
Dim keyByte() As Byte
Dim IVByte() As Byte
keyByte = System.Text.Encoding.ASCII.GetBytes(key)
IVByte = System.Text.Encoding.ASCII.GetBytes(iv)
Dim decryptor As ICryptoTransform = myRijndael.CreateDecryptor(keyByte, IVByte)
Dim sEncrypted As Byte() = Convert.FromBase64String(sEncryptedString)
Dim fromEncrypt() As Byte = New Byte(sEncrypted.Length) {}
Dim msDecrypt As New MemoryStream(sEncrypted)
Dim csDecrypt As New CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)
csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length)
Dim returnvalue = (System.Text.Encoding.ASCII.GetString(fromEncrypt))
Return returnvalue
Catch ex As Exception
Return ex.Message
End Try
End Function