js rsa 实现
RSA 加密算法实现
RSA 是一种非对称加密算法,广泛应用于数据加密和数字签名。以下是使用 JavaScript 实现 RSA 加密和解密的步骤。
生成 RSA 密钥对
使用 crypto.subtle.generateKey 方法生成 RSA 密钥对。密钥对包括公钥和私钥,公钥用于加密,私钥用于解密。
async function generateKeyPair() {
const keyPair = await window.crypto.subtle.generateKey(
{
name: "RSA-OAEP",
modulusLength: 2048,
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
hash: "SHA-256",
},
true,
["encrypt", "decrypt"]
);
return keyPair;
}
加密数据
使用公钥加密数据。加密前需要将明文转换为 ArrayBuffer 或 Uint8Array。
async function encryptData(publicKey, data) {
const encodedData = new TextEncoder().encode(data);
const encryptedData = await window.crypto.subtle.encrypt(
{
name: "RSA-OAEP",
},
publicKey,
encodedData
);
return encryptedData;
}
解密数据
使用私钥解密数据。解密后需要将 ArrayBuffer 转换为可读的字符串。
async function decryptData(privateKey, encryptedData) {
const decryptedData = await window.crypto.subtle.decrypt(
{
name: "RSA-OAEP",
},
privateKey,
encryptedData
);
const decodedData = new TextDecoder().decode(decryptedData);
return decodedData;
}
示例代码
以下是一个完整的示例,演示如何生成密钥对、加密和解密数据。

async function runExample() {
// 生成密钥对
const keyPair = await generateKeyPair();
// 明文数据
const plaintext = "Hello, RSA!";
// 加密
const encryptedData = await encryptData(keyPair.publicKey, plaintext);
console.log("Encrypted data:", encryptedData);
// 解密
const decryptedText = await decryptData(keyPair.privateKey, encryptedData);
console.log("Decrypted text:", decryptedText);
}
runExample().catch(console.error);
注意事项
- RSA 加密通常用于加密少量数据(如对称密钥),不适合直接加密大文件。
- 密钥长度建议至少为 2048 位以确保安全性。
- 浏览器环境中使用
crypto.subtleAPI,Node.js 中可以使用crypto模块。
通过以上方法,可以在 JavaScript 中实现 RSA 加密和解密功能。






