nodejs 用AES 给 protobuf 数据 加密与解密 用于记录防止忘了

// 导入必要的模块
const crypto = require('crypto');
const fs = require('fs');
const { ProtoBuf } = require("protobufjs");
 
//HmacMd5 加密
const HmacMd5Key = '123'; // 定义密钥
function encrypt(text) {
    const hash = crypto.createHmac('md5', HmacMd5Key);
    return hash.update(text).digest('hex');
}
const originalText = 'aaaa';
const encryptedText = encrypt(originalText);
console.log(encryptedText); 


// 定义 AES 加密解密
const algorithm = 'aes-256-cbc'; // 选择合适的算法
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);
const message = 'hello, world!';
// 加密
const cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = cipher.update(message, 'utf8', 'hex');
encrypted += cipher.final('hex');

// 解密
const decipher = crypto.createDecipheriv(algorithm, key, iv);
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');




// 读取并编译 protobuf 文件
ProtoBuf.loadSync('/path/to/your_pbfile.proto').then((root) => {
    const YourMessageType = root.lookupType("/packageName.YourMessageType");
    
    // 创建需要加密的消息对象
    const messageToEncrypt = YourMessageType.create({ field1: "value1", field2: "value2" });
  
    // 将消息序列化成二进制格式
    const buffer = YourMessageType.encode(messageToEncrypt).finish();
  
    // 使用 AES 加密函数进行加密
    const cipher = crypto.createCipheriv(algorithm, key, iv);
    let encryptedData = cipher.update(buffer);
    encryptedData = Buffer.concat([encryptedData, cipher.final()]);
  
    console.log(`加密后的数据:${encryptedData}`);
  
    // 保存加密后的数据到文件或发送给其他人
  
    // 从文件或接收来自其他人的加密数据
    const receivedBuffer = fs.readFileSync('/path/to/received_data.bin');
  
    // 使用 AES 解密函数进行解密
    const decipher = crypto.createDecipheriv(algorithm, key, iv);
    let decryptedData = decipher.update(receivedBuffer);
    decryptedData = Buffer.concat([decryptedData, decipher.final()]);
  
    console.log(`解密后的数据:${decryptedData}`);
  
    // 反序列化解密后的数据
    const decodedMessage = YourMessageType.decode(decryptedData);
  
    console.log(`解密后的消息内容:`, JSON.stringify(decodedMessage));
});

  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值