RSA加密是一种非对称加密算法,它使用两个密钥:一个公钥和一个私钥。公钥可以公开分享,用于加密数据,而私钥必须保密,用于解密数据。以下是关于RSA加密的一些基础概念、优势、类型、应用场景以及可能遇到的问题和解决方案:
crypto
模块)const crypto = require('crypto');
// 生成RSA密钥对
function generateKeyPair() {
return crypto.generateKeyPairSync('rsa', {
modulusLength: 2048, // 密钥长度
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem'
}
});
}
// 加密数据
function encryptData(publicKey, data) {
const buffer = Buffer.from(data);
const encrypted = crypto.publicEncrypt(publicKey, buffer);
return encrypted.toString('base64');
}
// 解密数据
function decryptData(privateKey, encryptedData) {
const buffer = Buffer.from(encryptedData, 'base64');
const decrypted = crypto.privateDecrypt(privateKey, buffer);
return decrypted.toString('utf8');
}
// 示例
const { publicKey, privateKey } = generateKeyPair();
const data = 'Hello, RSA!';
const encrypted = encryptData(publicKey, data);
console.log('Encrypted:', encrypted);
const decrypted = decryptData(privateKey, encrypted);
console.log('Decrypted:', decrypted);
const crypto = require('crypto');
// 生成RSA密钥对
const { publicKey, privateKey } = generateKeyPair();
// 生成AES密钥
const aesKey = crypto.randomBytes(32); // 256位AES密钥
// 加密数据
function encryptData(publicKey, data, aesKey) {
const iv = crypto.randomBytes(16); // 初始化向量
const cipher = crypto.createCipheriv('aes-256-cbc', aesKey, iv);
let encrypted = cipher.update(data, 'utf8', 'base64');
encrypted += cipher.final('base64');
const encryptedAesKey = crypto.publicEncrypt(publicKey, aesKey);
return {
iv: iv.toString('base64'),
encryptedAesKey: encryptedAesKey.toString('base64'),
encryptedData: encrypted
};
}
// 解密数据
function decryptData(privateKey, encryptedData) {
const aesKey = crypto.privateDecrypt(privateKey, Buffer.from(encryptedData.encryptedAesKey, 'base64'));
const iv = Buffer.from(encryptedData.iv, 'base64');
const decipher = crypto.createDecipheriv('aes-256-cbc', aesKey, iv);
let decrypted = decipher.update(encryptedData.encryptedData, 'base64', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
// 示例
const data = 'Hello, Hybrid RSA + AES!';
const encrypted = encryptData(publicKey, data, aesKey);
console.log('Encrypted:', encrypted);
const decrypted = decryptData(privateKey, encrypted);
console.log('Decrypted:', decrypted);
通过这种方式,可以在保证安全性的同时提高加密和解密的性能。
领取专属 10元无门槛券
手把手带您无忧上云