Search code examples
phpnode.jsmcrypt

How transform this mcrypt php code to the same code in nodejs?


I need to transform this php code :

$cipher_alg = MCRYPT_TRIPLEDES;
$key = "thekey";
$iv = mcrypt_create_iv(mcrypt_get_iv_size($cipher_alg, MCRYPT_MODE_ECB), MCRYPT_RAND);
$encrypted_string = mcrypt_encrypt($cipher_alg, $key, $string, MCRYPT_MODE_ECB, $iv);

return base64_encode($encrypted_string);

to nodejs.

I tested using https://github.com/tugrul/node-mcrypt but with the same string, the crypted result is not the same :

Code nodejs tested :

let blowfishCfb = new MCrypt('tripledes', 'ecb');
let iv = blowfishCfb.generateIv();
blowfishCfb.validateKeySize(false);
blowfishCfb.validateIvSize(false);
blowfishCfb.open('thekey', iv);

let ciphertext = blowfishCfb.encrypt(text);

return Buffer.concat([iv, ciphertext]).toString('base64');

Can you help to understand this ?

Thank,


Solution

  • do not concat the IV and the cypher together :

    let blowfishCfb = new MCrypt('tripledes', 'ecb');
    let iv = blowfishCfb.generateIv();
    blowfishCfb.validateKeySize(false);
    blowfishCfb.validateIvSize(false);
    blowfishCfb.open('thekey', iv);
    
    let ciphertext = blowfishCfb.encrypt(text);
    
    return ciphertext.toString('base64');