Skip to content

Instantly share code, notes, and snippets.

@zakcodez
Created October 6, 2021 01:17
Show Gist options
  • Save zakcodez/c3e1b3085fd114f7119f060c4b956c50 to your computer and use it in GitHub Desktop.
Save zakcodez/c3e1b3085fd114f7119f060c4b956c50 to your computer and use it in GitHub Desktop.
A script to encrypt and decrypt data using RSA public and private keys
const crypto = require("crypto");
const fs = require("fs");
// helper
function writeFile(file, data, callback = () => { }) {
fs.writeFile(file, data, (error) => {
if (error) throw error;
callback();
});
}
function generateKeys() {
crypto.generateKeyPair("rsa", {
modulusLength: 2048
}, (error, publicKey, privateKey) => {
if (error) throw error;
exportKeys(publicKey, privateKey, () => {
const data = "Some secret data";
const encrypted = crypto.publicEncrypt({
key: publicKey,
padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
oaepHash: "sha256"
}, Buffer.from(data));
const decrypted = crypto.privateDecrypt({
key: privateKey,
padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
oaepHash: "sha256"
}, encrypted);
console.log(decrypted.toString("utf-8") === data);
});
});
}
function exportKeys(publicKey, privateKey, callback = () => { }) {
writeFile("./private.key", privateKey.export({
format: "pem",
type: "pkcs1"
}), callback);
writeFile("./public.key", publicKey.export({
format: "pem",
type: "pkcs1"
}), callback);
}
generateKeys();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment