Encrypting in Coldfusion and then decrypting in PHP

后端 未结 2 719
不知归路
不知归路 2021-01-18 05:43

I have a problem reproducing the same result generated in PHP vs Coldfusion.

In PHP encrypting this way:



        
2条回答
  •  悲&欢浪女
    2021-01-18 06:24

    The problem is the padding. The mcrypt extension of PHP only uses ZeroPadding. It means that the plaintext is filled up with 0x00 bytes until the multiple of the block size is reached.

    PKCS#5/PKCS#7 padding on the other hand fills it up with bytes that denote the number of bytes missing until the next multiple of the block size. The block size for DES is 8 bytes.

    So you either need to pad the plaintext in php (See this drop-in code: A: How to add/remove PKCS7 padding from an AES encrypted string?) or use a different cipher in ColdFusion such as "DES/ECB/NoPadding". I recommend the former, because if you use NoPadding, the plaintext must already be a multiple of the block size.

    $key = "$224455@";
    $Valor = "TESTE";
    function pkcs7pad($plaintext, $blocksize)
    {
        $padsize = $blocksize - (strlen($plaintext) % $blocksize);
        return $plaintext . str_repeat(chr($padsize), $padsize);
    }
    
    $base = chop(base64_encode(mcrypt_encrypt(MCRYPT_DES, $key, pkcs7pad($Valor, 8), MCRYPT_MODE_ECB)));
    

    Result:

    qOQnhdxiIKs=

    Don't forget to unpad the recovered plaintext if you are decrypting in PHP.

提交回复
热议问题