Skip to content

Instantly share code, notes, and snippets.

@saltukalakus
Created December 3, 2019 14:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saltukalakus/f3a12cfa071523915e4fae88d176185a to your computer and use it in GitHub Desktop.
Save saltukalakus/f3a12cfa071523915e4fae88d176185a to your computer and use it in GitHub Desktop.
Encrypt & Decrypt with Node's crypto lib.
const crypto = require("crypto");
crypto.generateKeyPair(
"rsa",
{
modulusLength: 4096,
publicKeyEncoding: {
type: "spki",
format: "pem"
},
privateKeyEncoding: {
type: "pkcs8",
format: "pem",
cipher: "aes-256-cbc",
passphrase: "temp"
}
},
(err, publicKey, privateKey) => {
// Handle errors and use the generated key pair.
console.log(publicKey, privateKey);
const user = "STRING_TO_ENCRYPT";
const userTimeString = Buffer.from(user, "utf8");
const encryptedString = crypto.publicEncrypt(publicKey, userTimeString);
// const encrypted = Buffer.from(encryptedString, 'utf-8');
const decryptedString = crypto.privateDecrypt(
{
key: privateKey.toString(),
passphrase: "temp"
},
encryptedString
);
console.log(Buffer.from(encryptedString).toString("base64"));
console.log(decryptedString.toString("utf8"));
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment