rsa加密 nodejs
时间: 2023-10-10 14:08:11 浏览: 47
在 Node.js 中使用 RSA 加密,你可以使用 `crypto` 模块提供的 `crypto.publicEncrypt` 和 `crypto.privateDecrypt` 方法。以下是一个示例代码:
```javascript
const crypto = require('crypto');
// 加密
function encryptRSA(publicKey, plaintext) {
const buffer = Buffer.from(plaintext, 'utf8');
const encrypted = crypto.publicEncrypt(publicKey, buffer);
return encrypted.toString('base64');
}
// 解密
function decryptRSA(privateKey, ciphertext) {
const buffer = Buffer.from(ciphertext, 'base64');
const decrypted = crypto.privateDecrypt(privateKey, buffer);
return decrypted.toString('utf8');
}
// 示例用法
const publicKey = `-----BEGIN PUBLIC KEY-----
Your public key goes here
-----END PUBLIC KEY-----`;
const privateKey = `-----BEGIN PRIVATE KEY-----
Your private key goes here
-----END PRIVATE KEY-----`;
const plaintext = 'Hello World!';
const ciphertext = encryptRSA(publicKey, plaintext);
console.log('Encrypted:', ciphertext);
const decryptedText = decryptRSA(privateKey, ciphertext);
console.log('Decrypted:', decryptedText);
```
确保将你自己的公钥和私钥替换到示例代码中的 `publicKey` 和 `privateKey` 变量中。请注意,公钥和私钥应该是有效的 PEM 格式。
这个示例演示了如何使用 RSA 公钥加密和私钥解密文本数据。你可以根据自己的需求进行调整和扩展。