Created
December 3, 2019 14:08
-
-
Save saltukalakus/f3a12cfa071523915e4fae88d176185a to your computer and use it in GitHub Desktop.
Encrypt & Decrypt with Node's crypto lib.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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