// 引入依赖库
const rsa = require('node-rsa'); // 需要安装 node-rsa 库
// 创建一个新的 RSA 密钥对
const key = new rsa({ b: 512 }); // b 表示密钥长度,单位为 bit
// 获取公钥和私钥
const publicKey = key.exportKey('public'); // 导出公钥
const privateKey = key.exportKey('private'); // 导出私钥
console.log('Public Key:', publicKey);
console.log('Private Key:', privateKey);
// 加密数据
function encrypt(data) {
const encrypted = key.encrypt(data, 'base64', 'utf8'); // 使用公钥加密
return encrypted;
}
// 解密数据
function decrypt(encryptedData) {
const decrypted = key.decrypt(encryptedData, 'utf8'); // 使用私钥解密
return decrypted;
}
// 示例用法
const originalText = 'Hello, RSA!';
const encryptedText = encrypt(originalText);
console.log('Encrypted Text:', encryptedText);
const decryptedText = decrypt(encryptedText);
console.log('Decrypted Text:', decryptedText);
node-rsa
库来生成 RSA 密钥对并进行加解密操作。你需要通过 npm install node-rsa
来安装该库。new rsa({ b: 512 })
创建一个 512 位的 RSA 密钥对。你可以根据需要调整密钥长度。exportKey
方法可以分别导出公钥和私钥。encrypt
和 decrypt
分别用于加密和解密数据。加密时使用公钥,解密时使用私钥。希望这段代码对你有帮助!
上一篇:js delegate
下一篇:js function 返回值
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站