Skip to content

Instantly share code, notes, and snippets.

@thecipherBlock
Last active November 18, 2023 11:35
Show Gist options
  • Save thecipherBlock/fcca0db75ab00e1e5ee73cd294d32f7c to your computer and use it in GitHub Desktop.
Save thecipherBlock/fcca0db75ab00e1e5ee73cd294d32f7c to your computer and use it in GitHub Desktop.
Asymmetric encryption and decryption of JSON data in js
var crypto = require("crypto");
var path = require("path");
var fs = require("fs");
var encryptStringWithRsaPublicKey = function(toEncrypt, publicKeyInPemPath) {
var absolutePath = path.resolve(publicKeyInPemPath);
var publicKey = fs.readFileSync(absolutePath, "utf8");
var buffer = Buffer.from(JSON.stringify(toEncrypt));
var encrypted = crypto.publicEncrypt(publicKey, buffer);
return encrypted.toString("base64");
};
var decryptStringWithRsaPrivateKey = function(toDecrypt, privateKeyInPemPath) {
var absolutePath = path.resolve(privateKeyInPemPath);
var privateKey = fs.readFileSync(absolutePath, "utf8");
var buffer = Buffer.from(toDecrypt, "base64");
const decrypted = crypto.privateDecrypt(
{
key: privateKey.toString(),
},
buffer,
)
return decrypted.toString("utf8");
};
const { writeFileSync } = require('fs')
async function generateKeys() {
const _assymetricKeysInPem = await require('./generateKeypairFromSeed.js')(seedphrase);
writeFileSync('private.pem', _assymetricKeysInPem.privateKey)
writeFileSync('public.pem', _assymetricKeysInPem.publicKey)
}
(async () => {
await generateKeys();
let digest = encryptStringWithRsaPublicKey({
"A": "Apple",
"B": "Banana"
}, "public.pem");
let actualData = decryptStringWithRsaPrivateKey(digest, "private.pem");
console.log(b)
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment