Erik Landvall Erik Landvall - 2 months ago 14
Node.js Question

triple DES in nodejs compared to through openssl

fist of

xxd -p
in the following example adds "0a" in the end of the hex. No idea why, this is why you notice that I use the first parameter
$1
in the openssl encryption, I have generated the hex manually and inserted it as so..





#!/bin/bash
KEY=`echo $1 |xxd -p`;
openssl enc -e -des-ede -nosalt -K $1 -iv "0000000000000000" -in $2 -out $3;


called as so:

sh encrypt.sh 583645585458304c4f39524756514456 settings.conf settings.enc





in node.js however I use the following encryption:

const key = Buffer.from('X6EXTX0LO9RGVQDV');

module.exports = (file, callback) =>
{
const
iv = new Buffer(0),
cipher = require('crypto').createCipheriv('des-ede', key, iv);

callback(null, cipher.update(file, 'utf8', 'binary'));
}


...and trigger this as so:

require('fs').readFile(__dirname + '/settings.enc', (error, enc) =>
require('fs').readFile(__dirname + '/settings.conf', (error, conf) =>
require('./file-encrypt')(conf, (error, enc2) =>
{
enc2 = Buffer.from(enc2, 'binary');
console.log('compare: ', Buffer.compare(enc, enc2));
})));


But output is never "0" (meaning, they are never the same - tested with:
console.log('compare: ', Buffer.compare(enc2, enc2))
that ofc logs a beautiful
0
)

Why are these not equal?

Answer

You're missing a call to cipher.final() to get any remaining bytes after you are done providing all plaintext data. Try this instead:

const crypto = require('crypto');
const key = Buffer.from('X6EXTX0LO9RGVQDV');

module.exports = (file, callback) =>
{
  const iv = Buffer.alloc(0);
  const cipher = crypto.createCipheriv('des-ede', key, iv);
  callback(null, Buffer.concat([
    cipher.update(file),
    cipher.final()
  ]);
}

and use like:

require('fs').readFile(__dirname + '/settings.enc', (error, enc) =>
  require('fs').readFile(__dirname + '/settings.conf', (error, conf) =>
    require('./file-encrypt')(conf, (error, enc2) =>
    {
      console.log('compare: ', Buffer.compare(enc, enc2));
    })));

Also, you can omit the -iv "0000000000000000" from the openssl command line since the IV is not used by des-ede and avoids a warning printed to the console.

Comments