node 使用 crypto 对称加密 demo

文章介绍了如何在Node.js中使用crypto模块实现客户端与服务器之间的对称加密通信,包括用户输入密码的验证以及数据的加密和解密过程。
摘要由CSDN通过智能技术生成
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
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值