Last active
December 25, 2019 00:15
-
-
Save WolffDev/d37488603856c5072273e6dad72e2dbf to your computer and use it in GitHub Desktop.
Asymmetric encryption
This file contains hidden or 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
var crypto = require("crypto"); | |
var path = require("path"); | |
var fs = require("fs"); | |
const { PerformanceObserver, performance} = require('perf_hooks'); | |
const passphrase = "mySecret" | |
var encryptStringWithRsaPublicKey = function(toEncrypt, relativeOrAbsolutePathToPublicKey) { | |
var absolutePath = path.resolve(relativeOrAbsolutePathToPublicKey); | |
var publicKey = fs.readFileSync(absolutePath, "utf8"); | |
var buffer = new Buffer.from(toEncrypt); | |
var encrypted = crypto.publicEncrypt(publicKey, buffer); | |
return encrypted.toString("base64"); | |
}; | |
var decryptStringWithRsaPrivateKey = function(secretPass, toDecrypt, relativeOrAbsolutePathtoPrivateKey) { | |
var absolutePath = path.resolve(relativeOrAbsolutePathtoPrivateKey); | |
var privateKey = fs.readFileSync(absolutePath, "utf8"); | |
var buffer = new Buffer.from(toDecrypt, "base64"); | |
//var decrypted = crypto.privateDecrypt(privateKey, buffer); | |
const decrypted = crypto.privateDecrypt( | |
{ | |
key: privateKey.toString(), | |
passphrase: secretPass, | |
}, | |
buffer, | |
) | |
return decrypted.toString("utf8"); | |
}; | |
const { writeFileSync } = require('fs') | |
const { generateKeyPairSync } = require('crypto') | |
function generateKeys() { | |
const { publicKey, privateKey } = generateKeyPairSync('rsa', | |
{ | |
modulusLength: 2048, | |
namedCurve: 'secp256k1', | |
publicKeyEncoding: { | |
type: 'spki', | |
format: 'pem' | |
}, | |
privateKeyEncoding: { | |
type: 'pkcs8', | |
format: 'pem', | |
cipher: 'aes-256-cbc', | |
passphrase: passphrase | |
} | |
}); | |
writeFileSync('private.pem', privateKey) | |
writeFileSync('public.pem', publicKey) | |
} | |
const obs = new PerformanceObserver((items) => { | |
console.log(items.getEntries()[0].duration); | |
performance.clearMarks(); | |
}); | |
obs.observe({ entryTypes: ['measure'] }); | |
performance.mark('A'); | |
generateKeys(); | |
let a = encryptStringWithRsaPublicKey("hello", "public.pem") | |
let b = decryptStringWithRsaPrivateKey(passphrase, a, "private.pem"); | |
console.log('A ', a) | |
console.log('B ', b) | |
performance.mark('B'); | |
performance.measure('A to B', 'A', 'B'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment