Created
August 1, 2019 08:52
-
-
Save tonghuikang/81c24388f5ed4237c67a9e7ca3b55b62 to your computer and use it in GitHub Desktop.
Nodejs encrypt decrypt keygen asymmetric
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') | |
const path = require('path') | |
const fs = require('fs') | |
const { writeFileSync } = require('fs') | |
const { generateKeyPairSync } = require('crypto') | |
function generateKeys() { | |
const { privateKey, publicKey } = generateKeyPairSync('rsa', { | |
modulusLength: 4096, | |
publicKeyEncoding: { | |
type: 'pkcs1', | |
format: 'pem', | |
}, | |
privateKeyEncoding: { | |
type: 'pkcs1', | |
format: 'pem', | |
cipher: 'aes-256-cbc', | |
passphrase: '', | |
}, | |
}) | |
writeFileSync('private.pem', privateKey) | |
writeFileSync('public.pem', publicKey) | |
} | |
generateKeys() | |
function encrypt(toEncrypt, relativeOrAbsolutePathToPublicKey) { | |
const absolutePath = path.resolve(relativeOrAbsolutePathToPublicKey) | |
const publicKey = fs.readFileSync(absolutePath, 'utf8') | |
const buffer = Buffer.from(toEncrypt, 'utf8') | |
const encrypted = crypto.publicEncrypt(publicKey, buffer) | |
return encrypted.toString('base64') | |
} | |
function decrypt(toDecrypt, relativeOrAbsolutePathtoPrivateKey) { | |
const absolutePath = path.resolve(relativeOrAbsolutePathtoPrivateKey) | |
const privateKey = fs.readFileSync(absolutePath, 'utf8') | |
const buffer = Buffer.from(toDecrypt, 'base64') | |
const decrypted = crypto.privateDecrypt( | |
{ | |
key: privateKey.toString(), | |
passphrase: '', | |
}, | |
buffer, | |
) | |
return decrypted.toString('utf8') | |
} | |
const enc = encrypt('pik@chu', `public.pem`) | |
console.log('enc', enc) | |
const dec = decrypt(enc, `private.pem`) | |
console.log('dec', dec) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment