使用PHP mcrypt的AES128加密输出与ASP.net不同

时间:2014-06-26 16:14:05

标签: php asp.net encryption mcrypt

我有一个PHP应用程序需要加密ASP.net Web服务所使用的质询字符串,但我的PHP实现的输出没有被.net正确解密。正如关于iOS和.net的问题一样:AES128 bit encryption string is not similar as on .net

为什么输出不同,我可以对PHP输出与.net相同的内容?

我的PHP代码如下所示:

$key = '128bit-16bytekey';
$value = '128bit-16byteval';
function fnEncrypt($value, $key)
{
    $ivsize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
    $iv     = mcrypt_create_iv($ivsize);
    return base64_encode(
            mcrypt_encrypt(
                MCRYPT_RIJNDAEL_128,
                $key, $value, 
                MCRYPT_MODE_ECB,$iv
            ));
}
像这样

.net

public static string EncryptData(string plainText)
    {
        string encryptionKey = AppConstants.AES_ENCRYPTDECRYPT_KEY;
        // Convert our plaintext into a byte array.
        // Let us assume that plaintext contains UTF8-encoded characters.
        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

        // Use the password to generate pseudo-random bytes for the encryption
        // key. Specify the size of the key in bytes (instead of bits).
        ASCIIEncoding encoding = new ASCIIEncoding();
        byte[] keyBytes = new byte[16];

        byte[] tempKey = encoding.GetBytes(encryptionKey);

        for (int i = 0; i < keyBytes.Length; i++)
        {
            if (i < tempKey.Length)
            {
                keyBytes[i] = tempKey[i];
            }
            else
            {
                keyBytes[i] = 0;
            }
        }

        // Create uninitialized Rijndael encryption object.
        RijndaelManaged symmetricKey = new RijndaelManaged();

        //AesManaged symmetricKey = new AesManaged();


        //symmetricKey.Padding = PaddingMode.PKCS7;
        // It is reasonable to set encryption mode to Cipher Block Chaining
        // (CBC). Use default options for other symmetric key parameters.
        symmetricKey.Mode = CipherMode.ECB;

        // Generate encryptor from the existing key bytes and initialization 
        // vector. Key size will be defined based on the number of the key 
        // bytes.

        //ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes,initVectorBytes);
        ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, null);

        // Define memory stream which will be used to hold encrypted data.
        MemoryStream memoryStream = new MemoryStream();

        // Define cryptographic stream (always use Write mode for encryption).
        CryptoStream cryptoStream = new CryptoStream(memoryStream,
                                                     encryptor,
                                                     CryptoStreamMode.Write);
        // Start encrypting.
        cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);

        // Finish encrypting.
        cryptoStream.FlushFinalBlock();

        // Convert our encrypted data from a memory stream into a byte array.
        byte[] cipherTextBytes = memoryStream.ToArray();

        // Close both streams.
        memoryStream.Close();
        cryptoStream.Close();

        // Convert encrypted data into a base64-encoded string.
        string cipherText = Convert.ToBase64String(cipherTextBytes);

        // Return encrypted string.
        return cipherText;
    }

示例输出

PHP:Q54nP / tXq2rDTUwWw4ckkg ==

.net:Q54nP / tXq2rDTUwWw4ckkpSt9CQiIzsg2xsQEndcqc8 =

PHP:DQZdAB / lABXVOOoCdNM6HQ ==

.net:DQZdAB / lABXVOOoCdNM6HZSt9CQiIzsg2xsQEndcqc8 =

如上面的问题所示,.net输出的右侧始终相同,左侧在两个实现之间是一致的。我很确定IV是无关紧要的,它与mcrypt中如何处理填充有关。

如果我解密PHP中的任何一个输出,它会返回相同的正确结果。

任何人都可以光明吗?我无法更改.net应用。谢谢!

1 个答案:

答案 0 :(得分:0)

这是由于填充applied in .net而发生的。您可以通过在.net代码中添加以下行来解决此问题:

symmetricKey.Padding = PaddingMode.None;

或者您可以更改PHP代码以获取相同的加密字符串:

// Add the lines below to your fnEncrypt function
$block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
$len = strlen($value);
$padding = $block - ($len % $block);
$value .= str_repeat(chr($padding),$padding);

PHP手册页中的一条评论中描述了类似的问题:http://www.php.net//manual/en/function.mcrypt-encrypt.php#47973