node.js - 如何在 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);
解决方案
这段代码应该做你需要的。我们将创建一个解密函数,该函数使用相同的算法(显然还有密钥!)进行解密:
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'));
推荐阅读
- javascript - 在 voyager laravel 中提交任何表单时出现 js 错误
- android - Admob 更新,除非测试,否则不显示广告?
- python - AWS ServiceCatalog 预置产品错误
- swift - 为什么按钮在设置为隐藏时会在堆栈视图中移动?
- spring - 使用 Spring RabbitMessagingTemplate 发布消息时验证交换、路由密钥
- c# - 从带参数的方法中读取属性的值
- excel - EXCEL - 计算多个持续时间的总时间段而不重复重叠时间段的公式
- python - Python GTK 3+:我可以将“输入”信号用于组合框吗?
- excel - 双击标题以合并单元格VBA排序
- r - R 中的 h2o :当我的目标特征是二进制时,模型会产生一个负的 predClass 值。这是什么意思?