Search code examples
node.jsencryptionnode-crypto

How to decrypt Triple DES in Node.js


This code worked for me to encrypt, but how can I reverse it?

I have hashed the password in the database and I need to decrypt. I have both a key and a hash.

const crypto = require('crypto');
const md5 = text => {
  return crypto
    .createHash('md5')
    .update(text)
    .digest();
}

const encrypt = (text, secretKey) => {
  secretKey = md5(secretKey);
  console.log(secretKey.toString('base64'));
  secretKey = Buffer.concat([secretKey, secretKey.slice(0, 8)]); // properly expand 3DES key from 128 bit to 192 bit

  const cipher = crypto.createCipheriv('des-ede3', secretKey, '');
  const encrypted = cipher.update(text, 'utf8', 'base64');

  return encrypted + cipher.final('base64');
};
const encrypted = encrypt('testtext', 'testkey');

console.log(encrypted);

Solution

  • This code should do what you need. We'll create a decrypt function that decrypts using the same algorithm (and key obviously!):

    const crypto = require('crypto');
    const md5 = text => {
    return crypto
        .createHash('md5')
        .update(text)
        .digest();
    }
    
    const encrypt = (text, secretKey) => {
        secretKey = md5(secretKey);
        console.log(secretKey.toString('base64'));
        secretKey = Buffer.concat([secretKey, secretKey.slice(0, 8)]); // properly expand 3DES key from 128 bit to 192 bit
    
        const cipher = crypto.createCipheriv('des-ede3', secretKey, '');
        const encrypted = cipher.update(text, 'utf8', 'base64');
    
        return encrypted + cipher.final('base64');
    };
    
    const decrypt = (encryptedBase64, secretKey) => {
        secretKey = md5(secretKey);
        secretKey = Buffer.concat([secretKey, secretKey.slice(0, 8)]); // properly expand 3DES key from 128 bit to 192 bit
        const decipher = crypto.createDecipheriv('des-ede3', secretKey, '');
        let decrypted = decipher.update(encryptedBase64, 'base64');
        decrypted += decipher.final();
        return decrypted;
    };
    
    
    const encrypted = encrypt('testtext', 'testkey');
    console.log("Decrypted text:", decrypt(encrypted, 'testkey'));