使用 Node-RSA 实现 RSA 加密方案
小于 1 分钟
使用 Node-RSA 实现 RSA 加密方案
Node 端解密
1. 生成私钥并储存为 pem 文件
const k = new NodeRSA({ b: 512 }); //512 数字越大 越难破解 但是时间会长
const data = k.generateKeyPair();
const privateKey = data.exportKey("pkcs8-private-pem");
fs.writeFileSync("privateKey.pem", privateKey, { encoding: "utf-8" });2. 根据私钥生成公钥
NodeRSA(privateKey).exportKey("pkcs8-public-pem");3. 对密文解密
const privateKey = RsaUtil.generateKey();
const k = new nodeRsa(privateKey);
k.setOptions({
signingScheme: "pss-sha1",
encryptionScheme: "pkcs1_oaep",
});
const info = k.decrypt(ciphertext, "utf8");3. RsaUtil 文件
import * as nodeRsa from "node-rsa";
import NodeRSA = require("node-rsa");
import * as fs from "node:fs";
export class RsaUtil {
static getPublicKey(): string {
const privateKey = this.generateKey();
return new NodeRSA(privateKey).exportKey("pkcs8-public-pem");
}
static generateKey(): string {
if (fs.existsSync("privateKey.pem")) {
const privateKey = fs.readFileSync("privateKey.pem", {
encoding: "utf-8",
});
return privateKey;
}
const k = new nodeRsa({ b: 512 });
const data = k.generateKeyPair();
const privateKey = data.exportKey("pkcs8-private-pem");
fs.writeFileSync("privateKey.pem", privateKey, { encoding: "utf-8" });
return privateKey;
}
}