2

I'm trying to perform the same encryption operation in Java (using Bouncy Castle) and Node.js, however I receive different results in each language. Below are my attempted implementations - can anyone spot where I've gone wrong?

Java Code

//Java code:
import org.bouncycastle.crypto.engines.DESedeEngine;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.*;
//...
String inputString = "24778721";  //8 bytes
String keyString = "lf9aodkflaen7;ad";
BufferedBlockCipher cipher = new BufferedBlockCipher(new DESedeEngine());
byte[] key = keyString.getBytes();
byte[] input = inputString.getBytes();
cipher.init(isEncode, new KeyParameter(key));       

byte[] result = new byte[cipher.getOutputSize(input.length)];       
int outputLen = cipher.processBytes(input, 0, input.length, result, 0);
cipher.doFinal(result, outputLen);

//result is "65dcbb2e08e6d66e"

JavaScript Code

//node.js
var crypto = require('crypto');
var key = "lf9aodkflaen7;ad";
var data = "24778721";
var keybuf = new Buffer(key);
var databuf = new Buffer(data);

var cipher = crypto.createCipher('des-ede', keybuf);
cipher.update(databuf);
var result = cipher.final();

// result is "bf d2 cc 51 c5 e9 ef 38"

Alternative using createCipheriv function:

var cipher = crypto.createCipheriv('des-ede', keybuf.toString("binary"), '');
cipher.update(databuf);
var result = cipher.final();

// result is  "7a 24 bf 56 04 18 e3 6a"
Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
user798043
  • 63
  • 2
  • 6
  • 3
    The first step in such problems is to ensure you are using the same algorithm mode and padding in both environments. It seems like you are making use of the default choices from Bouncy Castle and Node.js. Find out what those defaults are. – Duncan Jones Dec 16 '13 at 08:49
  • In the sources of bouncycastle, 1)"new BufferedBlockCipher(new DESedeEngine())" has no padding processing 2) block_size in DESedeEngine is 8 bytes – user798043 Dec 18 '13 at 05:11
  • Yes, but node has default PKCS#7 padding. Using the double argument `createCipher` method obviously won't work either. – Maarten Bodewes Dec 19 '13 at 08:28

1 Answers1

1

You were almost there with the second try. This code will give you the same value like with Bouncy Castle:

//node.js
var crypto = require('crypto');
var key = "lf9aodkflaen7;ad";
var data = "24778721";
var keybuf = new Buffer(key);
var databuf = new Buffer(data);

var cipher = crypto.createCipheriv('des-ede', keybuf, '');
var crypted = cipher.update(databuf, 'utf8', 'hex');

console.log(crypted);
//65dcbb2e08e6d66e
Wiktor Zychla
  • 47,367
  • 6
  • 74
  • 106
lowselfesteemsucks
  • 825
  • 1
  • 13
  • 21