const crypto = require('crypto');
const readline = require('readline');
// 创建readline接口实例
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// 提示用户输入
rl.question('请输入密码: ', (answer) => {
check(answer)
// 不要忘记关闭接口实例!
rl.close();
});
function check(originalData){
// 原始数据 originalData
// 生成随机的对称加密密钥
const encryptionKey = crypto.randomBytes(32); // 256位密钥
const serverRes = server(encryptionKey)
console.log('服务器返回',serverRes)
// 创建加密器
const cipher = crypto.createCipher('aes-256-cbc', encryptionKey);
// 使用对称加密密钥对数据进行加密
let encryptedData = cipher.update(originalData, 'utf8', 'hex');
encryptedData += cipher.final('hex');
console.log('生成的加密编码:',encryptedData)
if(serverRes === encryptedData){
console.log(originalData,'输入正确')
}else{
console.log('输入错误')
}
// 创建解密器
const decipher = crypto.createDecipher('aes-256-cbc', encryptionKey);
// // 使用对称加密密钥对数据进行解密
// let decryptedData = decipher.update(encryptedData, 'hex', 'utf8');
// decryptedData += decipher.final('utf8');
// console.log('解密后的数据:', decryptedData);
}
function server(publicKey){
console.log('收到来自用户的公钥密码:',publicKey)
// 查询用户设置的保存密码
const userdata = '123456'
// 创建加密器
const cipher = crypto.createCipher('aes-256-cbc', publicKey);
// 使用对称加密密钥对数据进行加密
let encryptedData = cipher.update(userdata, 'utf8', 'hex');
encryptedData += cipher.final('hex');
return encryptedData
}
node 使用 crypto 对称加密 demo
最新推荐文章于 2024-07-17 15:26:15 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)