简体   繁体   English

如何在Node.js中解密3des

[英]How to decrypt 3des in nodejs

This code worked for me to encrypt but how to reverse ? 此代码对我有用,但可以加密吗? I have hashed password in database and i need to decrypt, i have key and hash both. 我在数据库中哈希了密码,我需要解密,我既拥有密钥又拥有哈希。

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

Thanks 谢谢

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM