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