首页 > 解决方案 > 如何在 Node.js 中解密三重 DES

问题描述

这段代码对我有用,但我怎样才能扭转它呢?

我已经对数据库中的密码进行了哈希处理,我需要解密。我有一个密钥和一个哈希。

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);

标签: node.jsencryptionnode-crypto

解决方案


这段代码应该做你需要的。我们将创建一个解密函数,该函数使用相同的算法(显然还有密钥!)进行解密:

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'));

推荐阅读