Node.js中加密和解密数据
mkdir crypto && cd crypto npm init -y npm install crypto --save
const crypto = require('crypto');
const algorithm = 'aes-256-ctr';
const secretKey = 'vOVH6sdmpNWjRRIqCc7rdxs01lwHzfr3';
const iv = crypto.randomBytes(16);
const encrypt = (text) => {
const cipher = crypto.createCipheriv(algorithm, secretKey, iv);
const encrypted = Buffer.concat([cipher.update(text), cipher.final()]);
return {
iv: iv.toString('hex'),
content: encrypted.toString('hex')
};
};
const decrypt = (hash) => {
const decipher = crypto.createDecipheriv(algorithm, secretKey, Buffer.from(hash.iv, 'hex'));
const decrpyted = Buffer.concat([decipher.update(Buffer.from(hash.content, 'hex')), decipher.final()]);
return decrpyted.toString();
};
module.exports = {
encrypt,
decrypt
};
加密和解密缓冲区
您也可以使用上面定义的功能对缓冲区进行加密和解密。 只需传递缓冲区代替字符串,它应该可以工作:
crypto-buffer.js
const { encrypt, decrypt } = require('./crypto');
const hash = encrypt(Buffer.from('Hello World!', 'utf8'));
console.log(hash);
// {
// iv: '692e44dbbea073fc1a8d1c37ea68dffa',
// content: 'bbffd902d55d7a00f3a0504e'
// }
const text = decrypt(hash);
console.log(text); // Hello World!
加密和解密流
您还可以使用加密模块对流进行加密和解密,如以下示例所示:
crypto-stream.js
const crypto = require('crypto');
const fs = require('fs');
const algorithm = 'aes-256-ctr';
const secretKey = 'vOVH6sdmpNWjRRIqCc7rdxs01lwHzfr3';
const iv = crypto.randomBytes(16);
// input file
const r = fs.createReadStream('file.txt');
// encrypt content
const encrypt = crypto.createCipheriv(algorithm, secretKey, iv);
// decrypt content
const decrypt = crypto.createDecipheriv(algorithm, secretKey, iv);
// write file
const w = fs.createWriteStream('file.out.txt');
// start pipe
r.pipe(encrypt)
.pipe(decrypt)
.pipe(w);
https://cloud.tencent.com/developer/article/1732824
https://github.com/attacomsian/code-examples/tree/master/nodejs/crypto