I have this php code
$plain_text = "abc";
$salt = "123";
echo $encrypted_text = openssl_encrypt($plain_text, "AES-128-ECB", $salt);
// result: kR/1uaFarptS5+n951MVsQ==
I have tried several methods (classes and functions) on vb.net, but the result of the encryption with this language is everytime not the same as above using php. For example this one:
Public Function AES_Encrypt (ByVal input As String, ByVal pass As String) As String
Dim AES As New System.Security.Cryptography.RijndaelManaged
Dim Hash_AES As New System.Security.Cryptography.MD5CryptoServiceProvider
Dim encrypted As String = ""
Try
Dim hash (31) As Byte
Dim temp As Byte () = Hash_AES.ComputeHash (System.Text.ASCIIEncoding.ASCII.GetBytes (pass))
Array.Copy (temp, 0, hash, 0, 16)
Array.Copy (temp, 0, hash, 15, 16)
AES.Key = hash
AES.Mode = Security.Cryptography.CipherMode.ECB
Dim DESEncrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateEncryptor
Dim Buffer As Byte () = System.Text.ASCIIEncoding.ASCII.GetBytes (input)
encrypted = Convert.ToBase64String (DESEncrypter.TransformFinalBlock (Buffer, 0, Buffer.Length))
Return encrypted
Catch ex As Exception
End Try
End Function
sEnc = AES_Encrypt("abc", "123")
Console.WriteLine(sEnc)
'result: Z3hCHcS0b2zJ7fEod3jcrw==
Please, with vb.net (no C#), how can I get the result "kR/1uaFarptS5+n951MVsQ==" which encryption of the text "abc" and salt "123" using the algorithm "AES-128-ECB"?
Due to the specification AES-128-ECB
in the PHP code, AES-128 is used in ECB mode, i.e. the key is 16 bytes long. But since only a 3 bytes large key is applied (123
), PHP pads to the necessary size of 16 bytes with 0x00
values. Note that if the key is too long, it will be truncated.
In the VB code a 32 bytes key is used. Since in .NET the keysize determines the AES variant, AES-256 is applied. Moreover, the passed key is not used directly, but the actual key is derived from the passed value with the digest MD5.
So that the VB code returns the result of the PHP code, the logic of the PHP code must be implemented in the VB code:
... 'Dim hash(31) As Byte 'Dim temp As Byte() = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(pass)) 'Array.Copy(temp, 0, hash, 0, 16) 'Array.Copy(temp, 0, hash, 15, 16) 'AES.Key = hash Dim keyPadded(15) As Byte Dim key = System.Text.ASCIIEncoding.ASCII.GetBytes(pass) Array.Copy(key, 0, keyPadded, 0, Math.Min(16, key.Length)) AES.Key = keyPadded ...
A few remarks:
$salt
. This is misleading, because a salt has a different meaning.123
is not a strong key (but maybe this is just a dummy value).123
does not represent a key, but a password from which a key is derived, then in general you should not use MD5, but specially designed algorithms like PBKDF2 or Argon2, see also here.