js rsa 实现
RSA 加密算法实现
RSA 是一种非对称加密算法,广泛应用于数据加密和数字签名。以下是 JavaScript 实现 RSA 加密和解密的方法。
生成 RSA 密钥对
使用 crypto.subtle.generateKey 方法生成 RSA 密钥对:

async function generateRSAKeyPair() {
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;
}
modulusLength: 密钥长度,通常为 2048 或 4096。publicExponent: 公钥指数,默认使用[0x01, 0x00, 0x01](即 65537)。hash: 哈希算法,支持 SHA-1、SHA-256、SHA-384 或 SHA-512。
加密数据
使用公钥加密数据:

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;
}
data: 需要加密的字符串或二进制数据。- 返回的
encryptedData是ArrayBuffer类型。
解密数据
使用私钥解密数据:
async function decryptData(privateKey, encryptedData) {
const decryptedData = await window.crypto.subtle.decrypt(
{
name: "RSA-OAEP",
},
privateKey,
encryptedData
);
return new TextDecoder().decode(decryptedData);
}
encryptedData: 加密后的ArrayBuffer数据。- 返回解密后的原始字符串。
导出和导入密钥
导出公钥
async function exportPublicKey(publicKey) {
const exported = await window.crypto.subtle.exportKey("spki", publicKey);
return window.btoa(String.fromCharCode(...new Uint8Array(exported)));
}
导入公钥
async function importPublicKey(base64Key) {
const binaryKey = Uint8Array.from(atob(base64Key), c => c.charCodeAt(0));
return await window.crypto.subtle.importKey(
"spki",
binaryKey,
{
name: "RSA-OAEP",
hash: "SHA-256",
},
true,
["encrypt"]
);
}
导出私钥
async function exportPrivateKey(privateKey) {
const exported = await window.crypto.subtle.exportKey("pkcs8", privateKey);
return window.btoa(String.fromCharCode(...new Uint8Array(exported)));
}
导入私钥
async function importPrivateKey(base64Key) {
const binaryKey = Uint8Array.from(atob(base64Key), c => c.charCodeAt(0));
return await window.crypto.subtle.importKey(
"pkcs8",
binaryKey,
{
name: "RSA-OAEP",
hash: "SHA-256",
},
true,
["decrypt"]
);
}
示例代码
以下是一个完整的 RSA 加密解密示例:
async function runRSADemo() {
// 生成密钥对
const keyPair = await generateRSAKeyPair();
// 导出公钥和私钥
const publicKeyBase64 = await exportPublicKey(keyPair.publicKey);
const privateKeyBase64 = await exportPrivateKey(keyPair.privateKey);
console.log("Public Key:", publicKeyBase64);
console.log("Private Key:", privateKeyBase64);
// 加密数据
const originalData = "Hello, RSA!";
const encryptedData = await encryptData(keyPair.publicKey, originalData);
// 解密数据
const decryptedData = await decryptData(keyPair.privateKey, encryptedData);
console.log("Decrypted Data:", decryptedData);
}
runRSADemo();
注意事项
- 密钥长度:RSA 密钥长度至少为 2048 位以确保安全性。
- 性能:RSA 加密和解密操作较慢,不适合加密大量数据。
- 浏览器支持:
crypto.subtleAPI 在现代浏览器中支持较好,但在某些旧版本中可能不可用。 - 密钥存储:私钥必须安全存储,避免泄露。
如果需要更高级的功能(如签名和验证),可以使用 sign 和 verify 方法。






