Node.js `crypto.final` makes the encrypted result different from PHP` mcrypt_encrypt`

Node.js crypto first.

// Both of key and IV are hex-string, but I hide them in Stackoverflow.

var secretKey  = new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), // 48 chars
    iv         = new Buffer('bbbbbbbbbbbbbbbb', 'hex'); // 16 chars
var str        = 'This string will be encrypted.';
var cipher     = crypto.createCipheriv('des-ede3-cbc', secretKey, iv),
    cryptedStr = cipher.update(str, 'utf8', 'base64') + cipher.final('base64');

Then PHP mcrypt.

$key    = pack('H*', "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); 
$iv     = pack('H*', "bbbbbbbbbbbbbbbb"); 
$string = 'This string will be encrypted.';
$text   = mcrypt_encrypt(MCRYPT_3DES, $key, $string, MCRYPT_MODE_CBC, $iv);
$text_base64 = base64_encode($text);

Problem.

On the same line, the same algorithm and the same encoding.

Nevertheless, there is a small part that does not coincide with cipher.final().

The real output is shown below.

// Node.js output.
UKBI17EIHKNM2EU48ygsjil5r58Eo1csByAIFp9GhUw=
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    Same part

// PHP output.
UKBI17EIHKNM2EU48ygsjil5r58Eo1csAY4C0JZoyco=
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    Same part

Why cipher.final()do different results?

How can the same results be done in Node.js , provided that they do not modify the PHP code .

+4
source share
1 answer

Since you cannot change your PHP code, you will need to change the node.js code.

, node.js 'crypto PKCS # 7, PHP . node.js(setAutoPadding(false)), :

function zeroPad(buf, blocksize){
    if (typeof buf === "string") {
        buf = new Buffer(buf, "utf8");
    }
    var pad = new Buffer((blocksize - (buf.length % blocksize)) % blocksize);
    pad.fill(0);
    return Buffer.concat([buf, pad]);
}

:

var secretKey  = new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), // 48 chars
    iv         = new Buffer('bbbbbbbbbbbbbbbb', 'hex'); // 16 chars
var str        = 'This string will be encrypted.';
var cipher     = crypto.createCipheriv('des-ede3-cbc', secretKey, iv);
cipher.setAutoPadding(false);

var cryptedStr = cipher.update(zeroPad(str, 8), 'utf8', 'base64') + cipher.final('base64');

console.log(cryptedStr);

:

UKBI17EIHKNM2EU48ygsjil5r58Eo1csAY4C0JZoyco=

:

function zeroUnpad(buf, blocksize){
    var lastIndex = buf.length;
    while(lastIndex >= 0 && lastIndex > buf.length - blocksize - 1) {
        lastIndex--;
        if (buf[lastIndex] != 0) {
            break;
        }
    }
    return buf.slice(0, lastIndex + 1).toString("utf8");
}
+3

All Articles