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;
}
加密数据
使用公钥加密数据:
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;
}
解密数据
使用私钥解密数据:
async function decryptData(privateKey, encryptedData) {
const decryptedData = await window.crypto.subtle.decrypt(
{
name: "RSA-OAEP",
},
privateKey,
encryptedData
);
return new TextDecoder().decode(decryptedData);
}
导出和导入密钥
导出公钥:
async function exportPublicKey(publicKey) {
const exported = await window.crypto.subtle.exportKey("spki", publicKey);
return window.btoa(String.fromCharCode(...new Uint8Array(exported)));
}
导入公钥:

async function importPublicKey(keyBase64) {
const binaryKey = Uint8Array.from(atob(keyBase64), c => c.charCodeAt(0));
const publicKey = await window.crypto.subtle.importKey(
"spki",
binaryKey,
{
name: "RSA-OAEP",
hash: "SHA-256",
},
true,
["encrypt"]
);
return publicKey;
}
完整示例
async function runExample() {
// 生成密钥对
const keyPair = await generateKeyPair();
// 导出公钥
const publicKeyBase64 = await exportPublicKey(keyPair.publicKey);
console.log("Public Key:", publicKeyBase64);
// 加密数据
const encrypted = await encryptData(keyPair.publicKey, "Hello RSA!");
console.log("Encrypted Data:", encrypted);
// 解密数据
const decrypted = await decryptData(keyPair.privateKey, encrypted);
console.log("Decrypted Data:", decrypted);
}
runExample();
注意事项
- RSA 加密有长度限制,通常不超过密钥长度减去填充字节数
- 对于大数据加密,建议使用对称加密算法如 AES,再用 RSA 加密对称密钥
- 实际应用中应妥善保管私钥,避免泄露
- Web Crypto API 仅在安全上下文(HTTPS 或 localhost)中可用
以上代码使用了现代浏览器支持的 Web Crypto API,无需额外库即可实现 RSA 加密功能。






