// 导入必要的模块
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));
});
nodejs 用AES 给 protobuf 数据 加密与解密 用于记录防止忘了
最新推荐文章于 2024-07-25 09:24:40 发布