1

I am trying to convert code the below java to Nodejs. I have one requirement to encrypt the text with a key using "DESede" algorithm. Currently code is written in Java and now I need to migrate to Nodejs

Java code -

public static void main(String args[]) throws Exception {

    String myString = "the sample text to be encrypted";

    EncryptData(myString);
}

public static byte[] EncryptData(String text) throws Exception {
    String keyValue = "kbhgvfbjhgfcf87576hgv656" ;
    final byte[] keyBytes = keyValue.getBytes("UTF8");

    final DESedeKeySpec key = new DESedeKeySpec(keyBytes);
    SecretKeyFactory keyFactory = 
    SecretKeyFactory.getInstance("DESede");
    SecretKey key1 = keyFactory.generateSecret(key);
    final Cipher cipher = Cipher.getInstance("DESede");
    cipher.init(1, key1);

    final byte[] plainTextBytes = text.getBytes("UTF8");
    final byte[] cipherText = cipher.doFinal(plainTextBytes);

    return cipherText;
}

I have tried using both NodeJS in built module Crypto and as well as CryptoJS. But getting different results than what I am getting in Java. Unable to figure out what I am missing.

Using CryptoJS [Google Code]-

function encrypt(message, key) {

    var keyHex = CryptoJS.enc.Utf8.parse(key);

    var encrypted = CryptoJS.DES.encrypt(message, keyHex, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });

    return encrypted;
}

Using NodeJS Crypto -

let option = {
        alg: 'des-ede3',
        key: "kbhgvfbjhgfcf87576hgv656",
        plaintext: "the sample text to be encrypted",
    }

encrypt(option);

function encrypt(param) {
    var key = new Buffer(param.key, 'utf8');
    var plaintext = new Buffer(param.plaintext, 'utf8');
    var alg = param.alg;

    //encrypt  
    var cipher = crypto.createCipheriv(alg, key, '');
    var ciph = cipher.update(plaintext, 'utf8');
    ciph += cipher.final('utf8');
    console.log(alg, ciph);
    return ciph;
}

I expect the output to be -

[-15, 6, -31, 6, -99, 57, -90, -125, 121, 73, -107, 112, -68, 8, 66, 62, 116, 71, 118, -55, -50, -21, 96, -124, 63, -75, -96, -117, 108, -46, -72]

but the actual output is - [5a ad e6 65 a1 be b9 68 d5 bd e4 9f 3c ca d6 6c 7e 71 ad 84 c6 39 81 49 14 35 7e 5f de 64 da 40].

Questions
  • 11
  • 1
  • In Java, the key is processed as bytes, in Node processed as UTF-8. See an example [here](https://stackoverflow.com/q/19698721/1820553) to match. – kelalaka Apr 30 '19 at 15:47
  • When I debugged the program, I noticed the line SecretKey key1 = keyFactory.generateSecret(key); alters the key and do the cipher. But in node JS I am not sure how to do that. When I use Des-ede algorithm I am getting Invalid Key length error. – Questions Apr 30 '19 at 18:50
  • The link has a solution. Also, I would like to add that you should not use DESede. You should use authenticated encryption as AES-GCM or Chacha-Poly1305. – kelalaka Apr 30 '19 at 19:11

0 Answers0