HamidYari
HamidYari

Reputation: 21

AES encryption different results, in C# and PHP

The problem is that I expect these 2 codes to return same value, but the results are not the same. The provided key and data are the same.

Here is the main code in C#. the result is: JzhfuV7T8BI9NnYsFdHIDw==

    public static RijndaelManaged GetCryptoTransform(string key)
    {
        string key_string64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(key));
        Console.WriteLine(key_string64);

        RijndaelManaged aes = new RijndaelManaged();
        aes.BlockSize = 128;
        aes.KeySize = 256;

        aes.Mode = CipherMode.CBC;
        aes.Padding = PaddingMode.PKCS7;

        byte[] keyArr = Convert.FromBase64String(key_string64);
        byte[] KeyArrBytes32Value = new byte[keyArr.Length];
        Array.Copy(keyArr, KeyArrBytes32Value, keyArr.Length);


        byte[] ivArr = { 1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1, 7, 7, 7, 7 };

        byte[] IVBytes16Value = new byte[16];


        Array.Copy(ivArr, IVBytes16Value, 16);

        aes.Key = KeyArrBytes32Value;
        aes.IV = IVBytes16Value;

        return aes;
    }
    public static string Encrypt(string PlainText, string key)
    {
        var aes = GetCryptoTransform(key);
        var encrypto = aes.CreateEncryptor();
        byte[] plainTextByte = ASCIIEncoding.UTF8.GetBytes(PlainText);


        byte[] CipherText = encrypto.TransformFinalBlock(plainTextByte, 0, plainTextByte.Length);

        return Convert.ToBase64String(CipherText);

    }

and here is the PHP code, the result is: ztykbceGV0SZqh/MyBInXQ==

function aes128_cbc_encrypt($key, $data) {
    $iv = "1234566543217777";
    $keyString = base64_encode ( $key );
    $padding = 16 - (strlen ( $data ) % 16);
    $data .= str_repeat ( chr ( $padding ), $padding );
    return mcrypt_encrypt ( MCRYPT_RIJNDAEL_128, $keyString, $data, MCRYPT_MODE_CBC, $iv );
}

Upvotes: 1

Views: 513

Answers (1)

zaph
zaph

Reputation: 112857

In C# the IV is an of an array of integer bytes, in PHP the IV is a character string, they are not the same.

Ex: The integer byte 1 has a value of 0x01, the character "1" has a value of 0x31.

Upvotes: 2

Related Questions