'Porting vb.net Rijndael encryption to PHP OpenSSL

I have to port some code for a customer from vb.net to PHP. Now vb.net is not really a language, which i'm using, so i have some problems there, porting a piece of encryption to PHP. Here is the vb.net source

Function EncryptString(ByVal Value As String, ByVal _password As String) As String

    Dim AES As New RijndaelManaged

    Dim md5 As New MD5CryptoServiceProvider
    Dim key() As Byte = md5.ComputeHash(Encoding.UTF8.GetBytes(_password))

    md5.Clear()
    AES.Key = key
    AES.GenerateIV()

    Dim iv() As Byte = AES.IV
    Dim ms As New MemoryStream

    ms.Write(iv, 0, iv.Length)

    Dim cs As New CryptoStream(ms, AES.CreateEncryptor, CryptoStreamMode.Write)
    Dim data() As Byte = System.Text.Encoding.UTF8.GetBytes(Value)

    cs.Write(data, 0, data.Length)
    cs.FlushFinalBlock()

    Dim encdata() As Byte = ms.ToArray()
    Return (Convert.ToBase64String(encdata))
    cs.Close()
    AES.Clear()

End Function

With PHP there is (was) the mcrypt module, which is now deprecated. So as i read we have to use openssl_encrypt from now on. The problem which i have is that i don't fully understand the vb.net code. Here is what i have so far, but it does not encrypt it correctly (i have the decrypt tool for testing, which is running also in vb.net).

function encrypt($string, $key, $iv = null) {
    $key = md5($key);
    $iv_size = openssl_cipher_iv_length('AES-128-CBC');
    if (!$iv) {
        $iv = openssl_random_pseudo_bytes($iv_size);
    }
    $encryptedMessage = openssl_encrypt($string, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
    return base64_encode($iv . $encryptedMessage);
}

Hopefully someone can give me an advise



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source