js rsa 实现
RSA 加密算法实现
RSA 是一种非对称加密算法,常用于数据加密和数字签名。以下是使用 JavaScript 实现 RSA 加密和解密的步骤。
生成密钥对
使用 crypto 模块生成 RSA 密钥对(适用于 Node.js 环境):

const crypto = require('crypto');
const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem'
}
});
console.log('Public Key:', publicKey);
console.log('Private Key:', privateKey);
加密数据
使用公钥加密数据:

function encryptWithPublicKey(publicKey, data) {
const bufferData = Buffer.from(data, 'utf8');
const encrypted = crypto.publicEncrypt(
{
key: publicKey,
padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
oaepHash: 'sha256'
},
bufferData
);
return encrypted.toString('base64');
}
const encryptedData = encryptWithPublicKey(publicKey, 'Hello, RSA!');
console.log('Encrypted Data:', encryptedData);
解密数据
使用私钥解密数据:
function decryptWithPrivateKey(privateKey, encryptedData) {
const bufferEncrypted = Buffer.from(encryptedData, 'base64');
const decrypted = crypto.privateDecrypt(
{
key: privateKey,
padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
oaepHash: 'sha256'
},
bufferEncrypted
);
return decrypted.toString('utf8');
}
const decryptedData = decryptWithPrivateKey(privateKey, encryptedData);
console.log('Decrypted Data:', decryptedData);
浏览器端实现
在浏览器中可以使用 SubtleCrypto API 实现 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 encoded = new TextEncoder().encode(data);
const encrypted = await window.crypto.subtle.encrypt(
{
name: 'RSA-OAEP'
},
publicKey,
encoded
);
return btoa(String.fromCharCode(...new Uint8Array(encrypted)));
}
async function decryptData(privateKey, encryptedData) {
const buffer = Uint8Array.from(atob(encryptedData), c => c.charCodeAt(0));
const decrypted = await window.crypto.subtle.decrypt(
{
name: 'RSA-OAEP'
},
privateKey,
buffer
);
return new TextDecoder().decode(decrypted);
}
// 使用示例
(async () => {
const keyPair = await generateKeyPair();
const encrypted = await encryptData(keyPair.publicKey, 'Hello, RSA!');
const decrypted = await decryptData(keyPair.privateKey, encrypted);
console.log('Decrypted:', decrypted);
})();
注意事项
- RSA 加密的数据长度有限制,通常建议加密短数据(如对称密钥)。
- 在实际应用中,建议结合 AES 等对称加密算法使用 RSA 加密对称密钥。
- 密钥管理和存储需谨慎,避免私钥泄露。
以上代码提供了 Node.js 和浏览器端的 RSA 实现方案,可根据具体需求选择适合的方式。






