Search code examples
node.jscryptojsdesnode-crypto

Implementing DES encryption in NodeJS (Crypto)


I'm trying to convert the below java function for DES encryption into NodeJS.

public static String decrypt (String value) {
    PBEParameterSpec pbeParamSpec = new PBEParameterSpec(SALT, COUNT);
    PBEKeySpec pbeKeySpec = new PBEKeySpec(KEY);
    SecretKeyFactory keyFac = SecretKeyFactory.getInstance(SECRET_KEY);
    SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
    Cipher dcipher = Cipher.getInstance(SECRET_KEY);
    dcipher.init(Cipher.DECRYPT_MODE, pbeKey, pbeParamSpec);
    byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(value);
    byte[] utf8 = dcipher.doFinal(dec);
    return new String(utf8, UTF8);
}

After some research, I was able to implement the below function in NodeJS.

function decrypt(input) {
        const encrypted = Buffer.from(input, 'base64')

        const key = crypto.pbkdf2Sync(SECRET_KEY, salt, ITERATION_COUNT, SECRET_KEY.length, 'md5');

        const cipher = crypto.createDecipher('des-cbc', key);

        const decrypted = Buffer.concat([cipher.update(encrypted, 'base64'), cipher.final()])

        return decrypted.toString('utf-8');
}

When I try to decrypt an already encrypted string, I'm getting some garbage value. Also, I don't understand where should I add the KEY value in NodeJS as in java code.

Please help me to understand what I'm doing wrong here.

UPDATE As mentioned by @Topaco in the comment, the name SECRET_KEY is misleading in the original java code. I found it as PBEWithMD5AndDES and was able to search with the same name and find a code snippet that solves my issue.

The code snippet is available as a gist: https://gist.github.com/qzaidi/5401800


Solution

  • As mentioned by @Topaco in the comment, the name SECRET_KEY is misleading in the original java code. I found it as PBEWithMD5AndDES and was able to search with the same name and find a code snippet that solves my issue.

    The code snippet is available as a gist: https://gist.github.com/qzaidi/5401800

    "use strict";
    
    /*
     * Emulates Java's PBEWITHMD5ANDDES for node.js
     */
    var crypto = require('crypto');
    
    var pbewithmd5anddes = {
    
      KDF: function(password, salt, iterations) {
        var pwd = new Buffer(password, 'utf-8');
        var key = Buffer.concat([pwd, salt]);
        var i;
        for (i = 0; i < iterations; i += 1) {
          key = crypto.createHash("md5").update(key).digest();
        }
        return key;
      },
    
      getKeyIV: function(password, salt, iterations) {
        var key = this.KDF(password, salt, iterations);
        var keybuf = new Buffer(key, 'binary').slice(0, 8);
        var ivbuf = new Buffer(key, 'binary').slice(8, 16);
        return [keybuf, ivbuf];
      },
    
      encrypt: function(payload, password, salt, iterations, cb) {
        var kiv = this.getKeyIV(password, salt, iterations);
        var cipher = crypto.createCipheriv('des', kiv[0], kiv[1]);
        var encrypted = [];
        encrypted.push(cipher.update(payload, 'utf-8', 'hex'));
        encrypted.push(cipher.final('hex'));
        return cb(undefined, new Buffer(encrypted.join(''), 'hex').toString('base64'));
      },
    
      decrypt: function(payload, password, salt, iterations, cb) {
        var encryptedBuffer = new Buffer(payload, 'base64');
        var kiv = this.getKeyIV(password, salt, iterations);
        var decipher = crypto.createDecipheriv('des', kiv[0], kiv[1]);
        var decrypted = [];
        decrypted.push(decipher.update(encryptedBuffer));
        decrypted.push(decipher.final());
        return cb(undefined, decrypted.join(''));
      }
    };
    
    module.exports = pbewithmd5anddes;
    
    /* ---------------- TEST CODE ---------------- */
    
    (function() {
      if (require.main === module) {
        var password = 'test';
        var iterations = 19;
        var salt = new Buffer('d99bce325735e303', 'hex');
        pbewithmd5anddes.encrypt('helloworld', password, salt, iterations, function(err, msg) {
          console.log('encrypted: ' + msg);
          // eat your own dogfood
          pbewithmd5anddes.decrypt(msg, password, salt, iterations, function(err, msg) {
            console.log('decrypted: ' + msg);
          });
        });
      }
    }());