AES加密在C#和PHP中的结果不同

时间:2017-01-29 12:38:14

标签: c# php encryption aes

问题是我希望这两个代码返回相同的值,但结果不一样。提供的密钥和数据是相同的。

这是C#中的主要代码。结果是: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);

    }

这是PHP代码,结果是: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 );
}

1 个答案:

答案 0 :(得分:1)

在C#中,IV是一个整数字节数组,在PHP中,IV是一个字符串,它们不一样。

Ex:整数字节1的值为0x01,字符"1"的值为0x31。