Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coldfusion 3DES encrypt make the encrypted result different to PHP `mcrypt_encrypt`

At first, Coldfusion Encrypt:

<cfset message = '1447841550'>
<cfset key = 'Mk9m98IfEblmPfrpsawt7BmxObt98Jev'>

<cfset ciphertext = Encrypt(#message#, #key#, "desede", "base64")>
<cfoutput>#ciphertext#</cfoutput>

Then, PHP mcrypt:

$message = "1447841550";
$key = 'Mk9m98IfEblmPfrpsawt7BmxObt98Jev';

$key = base64_decode($key);

$bytes = array(0,0,0,0,0,0,0,0); //byte [] IV = {0, 0, 0, 0, 0, 0, 0, 0}
$iv = implode(array_map("chr", $bytes));

$ciphertext = mcrypt_encrypt(MCRYPT_3DES, $key, $message, MCRYPT_MODE_CBC, $iv);

echo base64_encode($ciphertext);

Problem.

In the same string, same algorithm and same encoding.

Still there is a little part of the output that not match.

Below is the real sample output.

// Coldfusion output.

n6lp0I1w5FwrP3yPw3s8bw== 

^^^^^^^^^^

Same part


// PHP output.

n6lp0I1w5FxLQHskKMn4sw==

^^^^^^^^^^

Same part

Why Coldfusion make results different?

How I could make the same results in Coldfusion on condition that don't modify PHP code. PHP output is the correct output for me.

Is it possible to get the right result (PHP) with javascript? This solution is also good.

I'm frustrated.

like image 858
Juven Avatar asked Nov 20 '15 12:11

Juven


1 Answers

The settings are close, but not exactly the same. The reason the results differ is because:

  1. "CBC" mode requires an IV (initialization vector). The PHP code supplies an IV explicitly, but the CF code does not. So the encrypt() function generates an IV randomly. Hence why the results do not match: different IV, different result.

  2. When you use "NoPadding" mode, the input string must be padded so its length is an even multiple of the block size (ie DESEDE => 8). From what I understand, "...the mcrypt extension of PHP only uses ZeroPadding". The CF encrypt() function does not support zero padding. However, you can simulate it using something like this udf nullPad()

Once you have incorporated those two (2) changes, the results will match:

Results:

n6lp0I1w5FxLQHskKMn4sw== 

Example:

<cfset message = nullPad("1447841550", 8)>
<cfset key = "Mk9m98IfEblmPfrpsawt7BmxObt98Jev">
<!--- Important: IV values should be random, and NOT reused --->
<!--- https://en.wikipedia.org/wiki/Initialization_vector --->
<cfset iv = binaryDecode("0000000000000000", "hex")>
<cfset ciphertext = Encrypt(message, key, "DESede/CBC/NoPadding", "base64", iv)>
<cfoutput>#ciphertext#</cfoutput>
like image 121
Leigh Avatar answered Nov 18 '22 18:11

Leigh