Node.js / javascript encrypt AES-128 as mcrypt_ecb in PHP

I have a PHP code that encrypts an IP address in AES-128:

$ip = "MY_IP";
$secret = "MY_KEY";
$ip = @mcrypt_ecb(MCRYPT_RIJNDAEL_128, $secret, $ip, MCRYPT_ENCRYPT); 
$encrypted = bin2hex($ip);  // encrypted: 2854edb405cb7230ba1f4b87acddba8a

I need to make the same piece of code, but using javascript / node.js. I searched in the crypto node.js built-in module, but I could not reproduce the same result:

var crypto = require('crypto');
var ip = "MY_IP";
var secret = "MY_KEY";
var cipher = crypto.createCipher("AES-128-ECB", secret);
var encrypted = cipher.update(ip, 'utf8', 'hex');
encrypted += cipher.final('hex'); // encrypted: e84c06888696edda0139e98fc2c0a8cc

Does anyone have any ideas?

+4
source share
3 answers

I posted too fast, found a solution:

$> npm install mcrypt

And then the code:

var MCrypt = require('mcrypt').MCrypt;
var ip = "MY_IP";
var secret = "MY_KEY"
var desEcb = new MCrypt('rijndael-128', 'ecb');
desEcb.open(secret);
var cipherText = desEcb.encrypt(ip); // cipherText: 2854edb405cb7230ba1f4b87acddba8a

MCrypt github for further use of the encryption tool: https://github.com/tugrul/node-mcrypt

+3
source

The problem is that there are some things that PHP mcrypt (and node createCipher()) extends backstage that you probably don't know about.

, createCipher() , MD5 . , , createCipheriv(), ( IV), , PHP mcrypt. ECB IVs , IV.

-, PHP mcrypt , .

, AES-128-ECB , 16 . , crypto :

var crypto = require('crypto');

function makePadded(str) {
  var buf;
  var len = str.length;
  if (str.length % 16)
    len = str.length + (16 - str.length % 16);
  buf = new Buffer(len);
  buf.fill(0);
  buf.write(str, 0, str.length);
  return buf;
}

var ip = makePadded('MY_IP');
var secret = makePadded('MY_KEY');
var cipher = crypto.createCipheriv("AES-128-ECB", secret, '');
var encrypted = cipher.update(ip, 'binary', 'hex');
encrypted += cipher.final('hex');
// Slice off at 16 bytes to match the input length
encrypted = encrypted.slice(0, 32);

console.log(encrypted);

, , , MCRYPT_RIJNDAEL_128 PHP 128, 192 256 . PHP, 0 < keylen <= 16 128- , 192- , 16 < keylen <= 24 256- , 24 < keylen <= 32. node , node ​​ " ", PHP.

+2

in nodejs, the password must be a "binary" encoded string or buffer. in PHP obsolete @mcrypt_ecb expects the key to be a string

0
source

Source: https://habr.com/ru/post/1598394/


All Articles