Skip to content

Instantly share code, notes, and snippets.

@keksipurkki
Last active March 31, 2023 08:41
Show Gist options
  • Save keksipurkki/e67b743f1b8174c85712f4fa8b50a065 to your computer and use it in GitHub Desktop.
Save keksipurkki/e67b743f1b8174c85712f4fa8b50a065 to your computer and use it in GitHub Desktop.
RSA example in NodeJS
"use strict";

// Requires NodeJS >= 11.6.0

const crypto = require("crypto");
const util = require("util");

const generateKeyPair = util.promisify(crypto.generateKeyPair);

async function main() {

    const exportOptions = {
        format: "pem",
        type: "pkcs1"
    };

    const { privateKey, publicKey } = await generateKeyPair("rsa", {
        modulusLength: 2048,
    });

    const plainText = "A secret message";
    const cipherText = crypto.publicEncrypt(publicKey, Buffer.from(plainText));

    console.log("Keys: ")
    console.log(publicKey.export(exportOptions));
    console.log(privateKey.export(exportOptions));

    console.log("Plain text:", plainText);
    console.log("Cipher text:", cipherText.toString("hex"));

    const decrypted = crypto.privateDecrypt(privateKey, cipherText).toString();
    console.log("Decrypted:", decrypted);
    console.log("Success: ", decrypted === plainText);
}

main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment