在 Node.js 中使用 MD5、SHA、RSA 和 AES 加密算法
简介
在 Node.js 中,常用的加密算法包括 MD5、SHA、RSA 和 AES。本文将介绍如何使用这些算法进行数据加密和解密。
1. MD5 哈希算法
MD5 是一种常见的哈希算法,用于生成固定长度的哈希值。虽然它不适合加密敏感信息,但可以用于数据完整性校验。
示例代码
const crypto = require('crypto');
// 生成 MD5 哈希值
function generateMD5(data) {
return crypto.createHash('md5').update(data).digest('hex');
}
const data = "Hello, World!";
const hash = generateMD5(data);
console.log(`MD5: ${hash}`);
2. SHA 哈希算法
SHA(安全哈希算法)有多个版本,如 SHA-1、SHA-256 和 SHA-512。相比 MD5,SHA 更加安全。
示例代码
const crypto = require('crypto');
// 生成 SHA-256 哈希值
function generateSHA256(data) {
return crypto.createHash('sha256').update(data).digest('hex');
}
const data = "Hello, World!";
const hash = generateSHA256(data);
console.log(`SHA-256: ${hash}`);
3. RSA 加密与解密
RSA 是一种非对称加密算法,使用一对密钥(公钥和私钥)进行加密和解密。通常用于数据传输加密。
示例代码
const crypto = require('crypto');
// 生成 RSA 密钥对
function generateKeyPair() {
const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
});
return { publicKey, privateKey };
}
// RSA 加密
function encryptRSA(publicKey, data) {
return crypto.publicEncrypt(publicKey, Buffer.from(data)).toString('base64');
}
// RSA 解密
function decryptRSA(privateKey, encryptedData) {
return crypto.privateDecrypt(privateKey, Buffer.from(encryptedData, 'base64')).toString('utf-8');
}
const { publicKey, privateKey } = generateKeyPair();
const data = "Hello, RSA!";
const encryptedData = encryptRSA(publicKey, data);
console.log(`Encrypted RSA Data: ${encryptedData}`);
const decryptedData = decryptRSA(privateKey, encryptedData);
console.log(`Decrypted RSA Data: ${decryptedData}`);
4. AES 对称加密算法
AES(高级加密标准)是一种常用的对称加密算法,密钥用于加密和解密。
示例代码
const crypto = require('crypto');
// 生成随机 AES 密钥和初始化向量(IV)
const aesKey = crypto.randomBytes(32); // 256 位密钥
const iv = crypto.randomBytes(16); // 128 位 IV
// AES 加密
function encryptAES(data) {
const cipher = crypto.createCipheriv('aes-256-cbc', aesKey, iv);
let encrypted = cipher.update(data, 'utf-8', 'hex');
encrypted += cipher.final('hex');
return encrypted;
}
// AES 解密
function decryptAES(encryptedData) {
const decipher = crypto.createDecipheriv('aes-256-cbc', aesKey, iv);
let decrypted = decipher.update(encryptedData, 'hex', 'utf-8');
decrypted += decipher.final('utf-8');
return decrypted;
}
const data = "Hello, AES!";
const encryptedData = encryptAES(data);
console.log(`Encrypted AES Data: ${encryptedData}`);
const decryptedData = decryptAES(encryptedData);
console.log(`Decrypted AES Data: ${decryptedData}`);
总结
本文介绍了如何在 Node.js 中使用 MD5、SHA、RSA 和 AES 加密算法。MD5 和 SHA 用于生成哈希值,RSA 用于非对称加密和解密,而 AES 用于对称加密和解密。通过这些示例代码,你可以在 Node.js 项目中实现基本的数据加密和解密功能。