Implementing RSA Encryption Scheme using Node-RSA
12/11/24Less than 1 minute
Implementing RSA Encryption Scheme using Node-RSA
Node-side Decryption
1. Generate private key and save it as a pem file
const k = new NodeRSA({ b: 512 }); // 512 The larger the number, the harder it is to crack, but it takes longer
const data = k.generateKeyPair();
const privateKey = data.exportKey("pkcs8-private-pem");
fs.writeFileSync("privateKey.pem", privateKey, { encoding: "utf-8" });2. Generate public key from the private key
NodeRSA(privateKey).exportKey("pkcs8-public-pem");3. Decrypt ciphertext
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 File
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;
}
}JAVA-side Encryption (Mainly Android)
AI Translation | AI 翻译
This article was translated from Chinese to English by AI. If there are any inaccuracies, please refer to the original Chinese version.
本文由 AI 辅助从中文翻译为英文。如遇不准确之处,请以中文原版为准。
