推荐答案
// www.javascriptcn.com code example
// 引入 crypto-js 库
const CryptoJS = require("crypto-js");
// 生成 RSA 密钥对
const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem'
}
});
// 使用公钥加密数据
function encryptWithPublicKey(data, publicKey) {
const encrypted = crypto.publicEncrypt(publicKey, Buffer.from(data));
return encrypted.toString('base64');
}
// 使用私钥解密数据
function decryptWithPrivateKey(encryptedData, privateKey) {
const decrypted = crypto.privateDecrypt(privateKey, Buffer.from(encryptedData, 'base64'));
return decrypted.toString('utf8');
}
// 示例
const data = "Hello, RSA!";
const encryptedData = encryptWithPublicKey(data, publicKey);
console.log("Encrypted Data:", encryptedData);
const decryptedData = decryptWithPrivateKey(encryptedData, privateKey);
console.log("Decrypted Data:", decryptedData);本题详细解读
RSA 加密算法简介
RSA 是一种非对称加密算法,它使用一对密钥:公钥和私钥。公钥用于加密数据,私钥用于解密数据。RSA 的安全性基于大整数分解的困难性。
生成 RSA 密钥对
在 Node.js 中,可以使用 crypto 模块的 generateKeyPairSync 方法生成 RSA 密钥对。modulusLength 参数指定密钥的长度,通常为 2048 位。
加密过程
- 公钥加密:使用公钥对数据进行加密。加密后的数据是二进制格式,通常转换为 Base64 字符串以便传输或存储。
- 私钥解密:使用私钥对加密后的数据进行解密,还原出原始数据。
代码实现
- 引入库:使用
crypto模块进行 RSA 加密和解密操作。 - 生成密钥对:通过
generateKeyPairSync方法生成公钥和私钥。 - 加密函数:
encryptWithPublicKey函数使用公钥加密数据。 - 解密函数:
decryptWithPrivateKey函数使用私钥解密数据。
示例
在示例中,我们使用生成的公钥加密字符串 "Hello, RSA!",然后使用私钥解密,验证加密和解密的正确性。
注意事项
- 密钥管理:私钥必须严格保密,公钥可以公开。
- 性能:RSA 加密和解密操作相对较慢,通常用于加密小量数据或加密对称密钥。
- 数据长度限制:RSA 加密的数据长度受密钥长度限制,通常需要结合对称加密算法(如 AES)来处理大量数据。