最近平时项目中使用到加解密库比较多,所以整理了一些常用的加解密库,方便大家查阅使用,今天介绍的是crypto
库;
在 Node.js 中使用 crypto 模块可以实现多种加密、解密、哈希等安全相关操作,包括对称加密算法(如 AES、DES、3DES 等)、非对称加密算法(如 RSA、DSA 等)、消息摘要算法(如 MD5、SHA-1、SHA-256 等)等。下面是一些使用 crypto 模块的示例:
对称加密
使用对称加密算法可以加密和解密数据,使用的密钥是相同的。
const crypto = require('crypto');
// 创建密钥和向量
const key = Buffer.from('000102030405060708090a0b0c0d0e0f', 'hex');
const iv = Buffer.from('101112131415161718191a1b1c1d1e1f', 'hex');
// 加密数据
const plaintext = 'hello, world!';
const cipher = crypto.createCipheriv('aes-128-cbc', key, iv);
let ciphertext = cipher.update(plaintext, 'utf8', 'base64');
ciphertext += cipher.final('base64');
console.log(ciphertext);
// 解密数据
const decipher = crypto.createDecipheriv('aes-128-cbc', key, iv);
let decrypted = decipher.update(ciphertext, 'base64', 'utf8');
decrypted += decipher.final('utf8');
console.log(decrypted);
在上述代码中,我们使用 crypto 模块创建了一个密钥和向量,并使用 crypto.createCipheriv 方法创建了一个 Cipher 对象,使用 AES-128-CBC 算法将消息 hello, world! 加密。然后,我们使用 update 方法更新 Cipher 对象的输入数据,最后使用 final 方法获取加密后的数据。最后,我们使用 crypto.createDecipheriv 方法创建了一个 Decipher 对象,并使用相同的密钥和向量解密加密后的数据。
非对称加密
使用非对称加密算法可以加密和解密数据,使用的密钥是不同的,包括公钥和私钥。
const crypto = require('crypto');
// 创建公钥和私钥
const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: {
type: 'pkcs1',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs1',
format: 'pem'
}
});
// 加密数据
const plaintext = 'hello, world!';
const ciphertext = crypto.publicEncrypt(publicKey, Buffer.from(plaintext)).toString('base64');
console.log(ciphertext);
// 解密数据
const decrypted = crypto.privateDecrypt(privateKey, Buffer.from(ciphertext, 'base64')).toString('utf8');
console.log(decrypted);
在上述代码中,我们使用 crypto 模块生成了一个 RSA 密钥对,然后使用 crypto.publicEncrypt 方法使用公钥加密消息 hello, world!。最后,我们使用 crypto.privateDecrypt 方法使用私钥解密密文。
哈希
使用哈希算法可以生成消息的摘要,通常用于保证消息完整性和防篡改。常见的哈希算法包括 MD5、SHA-1、SHA-256 等。
const crypto = require('crypto');
// 计算 MD5 摘要
const message = 'hello, world!';
const hash = crypto.createHash('md5');
hash.update(message, 'utf8');
const digest = hash.digest('hex');
console.log(digest);
在上述代码中,我们使用 crypto 模块创建了一个 Hash 对象,并使用 update 方法将消息 hello, world! 添加到 Hash 对象中,然后使用 digest 方法计算消息的摘要。
HMAC
使用 HMAC(Hash-based Message Authentication Code)算法可以生成消息的签名,用于验证消息的完整性和防篡改。
const crypto = require('crypto');
// 计算 HMAC-SHA256 签名
const message = 'hello, world!';
const secret = 'my-secret';
const hmac = crypto.createHmac('sha256', secret);
hmac.update(message, 'utf8');
const signature = hmac.digest('hex');
console.log(signature);
在上述代码中,我们使用 crypto 模块创建了一个 Hmac 对象,并使用 update 方法将消息 hello, world! 添加到 Hmac 对象中,然后使用 digest 方法计算消息的 HMAC-SHA256 签名。
除了以上示例,crypto 模块还提供了其他许多加密、解密、哈希等方法,可以根据具体需求使用相应的方法。