Un-encrypting / re-encrypting a ColdFusion encrypted string in PHP

I’m in the unenviable position where I have to maintain functionality with an existing ColdFusion application. As part of it’s login process the Coldfusion app stores a cookie with an encrypted string.

encrypt(strToEncrypt, theKey, "AES", "Base64")

I can successfully decrypt this string in PHP using MCrypt and the following code

    MCRYPT_MODE_ECB, "0000000000000000")

I now have the need to perform the same encryption within PHP so that the ColdFusion app can access the data in the cookie.

At the moment what I have is

mcrypt_encrypt( MCRYPT_RIJNDAEL_128, base64_decode($theKey), $strToEncrypt, MCRYPT_MODE_ECB, "0000000000000000");

This, however, is incompatible with the equivalent ColdFusion encryption algorithm

decrypt(strToDecrypt, theKey, "AES", "Base64")

Throwing a Given final block not properly padded error.

Any help much appreciated.


Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Don’t know how much help this will be but I have had the following working. I think to make CF happy you have to pad your encryption to a certain length

Encrypt in CF

Encrypt(data, encKey, 'AES/CBC/PKCS5Padding', encoding, encIv)

Decrypt in PHP

function Decode($data, $encKey, $encIv, $format = 'uu') {
    if ($format === 'uu') {
        $data = Convert_uudecode($data);
    } else if ($format === 'hex') {
        $data = Pack('H*', $data);
    } else if ($format === 'base64') {
        $data = Base64_Decode($data);
    } else if ($format === 'url') {
        $data = UrlDecode($data);
    $data = MCrypt_decrypt(MCRYPT_RIJNDAEL_128, $encKey, $data, 'cbc', $encIv);
    $pad = Ord($data{strlen($data)-1});
    if ($pad > strlen($data)) return $data;
    if (strspn($data, chr($pad), strlen($data) - $pad) != $pad) return $data;
    return substr($data, 0, -1 * $pad); 

Encrypt in PHP

function Encode($data, $encKey, $encIv, $format = 'uu') {
    $pad = 16 - (StrLen($data) % 16);
    if ($pad > 0) {
        $data .= Str_repeat(Chr($pad), $pad);
    $data = MCrypt_encrypt(MCRYPT_RIJNDAEL_128, $encKey, $data, 'cbc', $encIv);
    if ($format === 'uu') {
        return Convert_uuencode($data);
    } else if ($format === 'hex') {
        return Bin2Hex($data);
    } else if ($format === 'base64') {
        return Base64_Encode($data);
    } else if ($format === 'url') {
        return UrlEncode($data);

Decrypt in CF

Decrypt(data, encKey, 'AES/CBC/PKCS5Padding', encoding, encIv)

For some reason that I can’t remember, I favoured ‘uu’ for the encoding.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply