PHP C#MCRYPT_RIJNDAEL_128

时间:2017-03-20 15:28:44

标签: c# php encryption

我尝试在PHP和C#中进行加密(使用MCRYPT_RIJNDAEL_128 Cipher CBC),但输出不匹配。

key = '1234567812345678';
iv = '1234567812345678';

PHP:

function Encrypt($data, $key, $iv) {
    return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, base64_encode($data), MCRYPT_MODE_CBC, $iv));
}

C#:

public static string Encrypt(string plainText, string key, string iv)
{
    byte[] initVectorBytes = Encoding.ASCII.GetBytes(iv);
    byte[] plainTextBytes = Encoding.ASCII.GetBytes(plainText);
    byte[] keyBytes = Encoding.ASCII.GetBytes(key);
    using (RijndaelManaged symmetricKey = new RijndaelManaged())
    {
        symmetricKey.Mode = CipherMode.CBC;
        symmetricKey.Padding = PaddingMode.Zeros;
        symmetricKey.KeySize = 128;
        symmetricKey.BlockSize = 128;
        using (ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes))
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                {
                    cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                    cryptoStream.FlushFinalBlock();
                    byte[] cipherTextBytes = memoryStream.ToArray();
                    return Convert.ToBase64String(cipherTextBytes);
                }
            }
        }
    }
}

帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

我认为您的问题在于您的PHP代码。

mcrypt_encrypt函数希望数据(需要编码)采用纯文本格式,因此您不需要额外的base64_encode,因为您正在使用字符串。将keyiv传递给函数的方法相同,您应该将data变量传递给它。 (未测试的)

function Encrypt($data, $key, $iv) {
    return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv));
}

让我知道你的进步,以便我将来可以帮助你解决这个问题:)