Page 1 of 1

Answer in cryptoJS and mcrypt is not the same

Posted: Mon Jun 23, 2014 3:41 pm
by patrickroi
I have a cryptoJS script the returns an output

Code: Select all

Y44Ktqd/b2VpbdUFaXR8bg==
if I try encrypting the string 'Patrick'. But when I use mcrypt the output is like

Code: Select all

8qFvpRnDDifn4L3SE1e4uWG1G6CDeE8A
.

I want them to be perfectly matched but I tried everything. Here are the codes.

CryptoJS function

Code: Select all

function crypto_encrypt(text) {                                                                            //This is for JS
var keyBase64 = CryptoJS.enc.Base64.parse("ITU2NjNhI0tOc2FmZExOTQ==");
var iv = CryptoJS.enc.Base64.parse('AAAAAAAAAAAAAAAAAAAAAA==');

var encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(text), keyBase64,
    {
        keySize: 128 / 8,
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
        //padding: CryptoJS.pad.ZeroPadding
    });

// Returns a Base64 encoded string.
return encrypted;
}


and here's the mcrypt


Code: Select all

<?php
$Pass = "Password";
    $Clear = "Patrick";
//$sSecretKey = ("ITU2NjNhI0tOc2FmZExOTQ==");       

$crypted = fnEncrypt($Clear, $Pass);
    echo "EncrypTed: ".$crypted."</br>";

$newClear = fnDecrypt($crypted, $Pass);
    echo "Decrypted: ".$newClear."</br>"; 



function fnEncrypt($sValue, $sSecretKey)
{
 $iv = base64_decode('AAAAAAAAAAAAAAAAAAAAAA==');
     $sSecretKey = base64_decode('ITU2NjNhI0tOc2FmZExOTQ==');

return     rtrim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_192,$sSecretKey,$sValue,MCRYPT_MODE_CBC,   $iv)), "\0");
}

function fnDecrypt($sValue, $sSecretKey)
{
return utf8_decode(rtrim(
    mcrypt_decrypt(
        MCRYPT_RIJNDAEL_192, 
        base64_decode('ITU2NjNhI0tOc2FmZExOTQ=='), 
        base64_decode($sValue), 
            MCRYPT_MODE_CBC,
            $iv = base64_decode('AAAAAAAAAAAAAAAAAAAAAA==')
    ), "\0"
)
);
}
?>

I just want to get the same result from those 2 (cryptoJS and mcrypt in PHP)


^Thanks,.

Re: Answer in cryptoJS and mcrypt is not the same

Posted: Mon Jun 23, 2014 9:49 pm
by Weirdan
This kind of problems often arise when libraries use different padding. mcrypt uses zero padding for both key and data being encrypted.
It's also likely you're using different key lenghts - 128 bits on js side and 192 bits on php side (guess where that 192 comes from in RIJNDAEL_192).

Re: Answer in cryptoJS and mcrypt is not the same

Posted: Mon Jun 23, 2014 9:56 pm
by Weirdan
Also see http://www.leaseweblabs.com/2014/02/aes ... y-padding/ - it briefly explains differences between AES and Rijndael, as it applies to mcrypt and php.