Last active
November 18, 2023 11:35
-
-
Save thecipherBlock/fcca0db75ab00e1e5ee73cd294d32f7c to your computer and use it in GitHub Desktop.
Asymmetric encryption and decryption of JSON data in js
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
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