📜  Node.js 加密完整参考(1)

📅  最后修改于: 2023-12-03 15:03:15.267000             🧑  作者: Mango

Node.js 加密完整参考

Node.js 加密模块提供了一系列的加密方法,包括了对称加密(如 AES,DES),非对称加密(如 RSA),哈希算法(如 SHA256,MD5)等等。这些功能可以让开发者轻松地实现信息安全的需求。

加密模块概述

Node.js 的加密模块可分为以下几类:

  • 对称加密:使用相同的密钥同时进行加密和解密。
  • 非对称加密:使用一对密钥进行加密和解密,公钥加密的内容只能使用相应的私钥进行解密。
  • 哈希算法:将原始数据映射为固定长度的字节序列,常用于数据校验和、数字签名等场景。
对称加密

Node.js 支持的对称加密算法包括:

  • AES(Advanced Encryption Standard):目前广泛使用的对称加密算法,支持多种加密位数(128、192、256),通常安全性较高。
  • DES(Data Encryption Standard):较为古老的对称加密算法,安全性较低,在实际应用中已被取代。
  • 3DES(Triple Data Encryption Standard):基于 DES,将加密操作进行了三次,提高安全性,但效率较低。
const crypto = require('crypto');
const algorithm = 'aes-256-cbc'; // 加密算法
const key = 'mysecretkey'; // 密钥
const input = 'Hello, world!'; // 加密内容
let cipher = crypto.createCipher(algorithm, key); // 创建加密器
let encrypted = cipher.update(input, 'utf8', 'hex'); // 加密输入内容
encrypted += cipher.final('hex'); // 补全加密内容
console.log(encrypted); // 输出:a79af145cb8b0a2a0f26b2781d6b74c6
非对称加密

Node.js 支持的非对称加密算法主要有:

  • RSA(Rivest–Shamir–Adleman):最广泛使用的非对称加密算法之一,可用于数字签名、密钥协商等场景。
  • ECC(Elliptic Curve Cryptography):相比 RSA,ECC 提供了更高的安全性和更小的密钥尺寸,在一些场景下更为适用。
const crypto = require('crypto');
const algorithm = 'rsa'; // 非对称加密算法
const plaintext = 'Hello, world!'; // 原始数据
const keyPair = crypto.generateKeyPairSync(algorithm, { modulusLength: 4096 }); // 生成密钥对
const publicKey = keyPair.publicKey; // 公钥
const privateKey = keyPair.privateKey; // 私钥

// 使用公钥进行加密
let encrypted = crypto.publicEncrypt(publicKey, Buffer.from(plaintext, 'utf8')).toString('base64');
console.log(encrypted); // 输出:MFX2r3X3fkDjXP/DhEvlkR/mohpA8hxhSlG90pYkB1abvRUurWnXsmCTnT2TJPrfnKYvCftxWGu8+oM2a/koExeZAIopJZ0/NzaN0+SuAQZY1wkvxiMN0ofjJdO5I09/JIkf5G5HvgS5OeyuLNs/l+V7yJ2Q4Oq7YhYUVPgllUc=

// 使用私钥进行解密
let decrypted = crypto.privateDecrypt(privateKey, Buffer.from(encrypted, 'base64')).toString('utf8');
console.log(decrypted); // 输出:Hello, world!
哈希算法

哈希算法是一种将任意数据压缩(hash)成固定长度的字节序列的技术,常用于校验和、数字签名、密码存储等场景。Node.js 支持的哈希算法包括:

  • SHA256(Secure Hash Algorithm 256 bits):SHA 系列中较新且安全性较高的哈希算法,生成长度为 256 比特的哈希值。
  • MD5(Message-Digest Algorithm 5):比 SHA 系列更快但安全性更低的哈希算法,生成长度为 128 比特的哈希值。
const crypto = require('crypto');
const algorithm = 'sha256'; // 哈希算法
const plaintext = 'Hello, world!';
let hash = crypto.createHash(algorithm); // 创建哈希对象
hash.update(plaintext, 'utf8'); // 哈希输入内容
console.log(hash.digest('hex')); // 输出:6f5902ac237024bdd0c176cb93063dc4d5955b5d5c5ae2044c8c2af4b3faa2a5
常用加密应用示例
加密文件

使用 AES 可以对文件进行加密,实现对敏感信息的保护。加密过程中需要密钥、初始化向量等参数,解密时需要相同的参数。

const crypto = require('crypto');
const fs = require('fs');
const algorithm = 'aes-256-cbc'; // 加密算法
const key = 'mysecretkey'; // 密钥
const iv = crypto.randomBytes(16); // 初始化向量
const inputFilename = 'input.txt'; // 输入文件名
const outputFilename = 'output.enc'; // 输出文件名
const input = fs.readFileSync(inputFilename); // 读取输入文件内容
let cipher = crypto.createCipheriv(algorithm, key, iv); // 创建加密器
let encrypted = cipher.update(input, null, 'hex'); // 加密输入内容
encrypted += cipher.final('hex'); // 补全加密内容
let output = Buffer.from(encrypted, 'hex'); // 将加密内容转换为二进制数据
output = Buffer.concat([iv, output], iv.length + output.length); // 拼接初始化向量和加密结果
fs.writeFileSync(outputFilename, output); // 将结果写入输出文件
console.log('Encrypted successfully!');
对上传数据进行加密

在客户端发送数据到服务器之前,可以使用加密算法对数据进行加密,保护数据隐私。

const crypto = require('crypto');
const http = require('http');
const qs = require('querystring');
const algorithm = 'aes-256-cbc'; // 加密算法
const key = 'mysecretkey'; // 密钥
const iv = crypto.randomBytes(16); // 初始化向量
const data = { username: 'alice', password: '123456' }; // 待上传数据
let cipher = crypto.createCipheriv(algorithm, key, iv); // 创建加密器
let content = qs.stringify(data); // 将数据转换为表单格式
let encrypted = cipher.update(content, 'utf8', 'hex'); // 加密表单内容
encrypted += cipher.final('hex'); // 补全加密内容
let body = Buffer.from(encrypted, 'hex'); // 将加密内容转换为二进制数据
let headers = {
  'Content-Type': 'application/octet-stream',
  'Content-Length': body.length,
  'X-Initialization-Vector': iv.toString('hex'), // 传递初始化向量
};
let options = { method: 'POST', path: '/login', headers: headers };
let req = http.request(options, (res) => {
  console.log(`statusCode: ${res.statusCode}`);
  res.on('data', (d) => {
    process.stdout.write(d);
  });
});
req.write(body); // 发送加密数据
req.end();
对密码进行加密存储

将用户的密码存储在数据库中时,可以使用哈希算法将其转换为不可逆的散列值,使得在密码泄漏的情况下,攻击者无法直接获取密码。常用的哈希算法包括 SHA256、MD5 等。

const crypto = require('crypto');
const user = { username: 'alice', password: '123456' };
const algorithm = 'sha256'; // 哈希算法
const salt = crypto.randomBytes(8).toString('hex'); // 盐值
const pepper = 'mysecretpepper'; // 唯一密钥
const hash = crypto.createHash(algorithm); // 创建哈希对象
hash.update(user.password + salt + pepper, 'utf8'); // 哈希密码+盐值+密钥
const hashedPassword = hash.digest('hex'); // 生成散列值
console.log(`Salt: ${salt}`);
console.log(`Hashed password: ${hashedPassword}`);
结论

通过 Node.js 的加密模块,我们可以轻松地实现对称加密、非对称加密和哈希算法等功能。在实际应用中,我们可以将这些功能用于加密文件、保护数据隐私、存储密码等场景,提高系统的安全性和可靠性。