Last active
December 24, 2023 17:35
-
-
Save claretnnamocha/57f14084e0c08f1efcccd2564f960dec to your computer and use it in GitHub Desktop.
Simple E2E encryption strategy
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
import { decrypt, encrypt, generatePrivate, getPublic } from "eccrypto"; | |
// setup | |
let privateKey = generatePrivate(); | |
let publicKey = getPublic(privateKey); | |
let frontendPublicKey = publicKey.toString("hex"); | |
let backendPrivateKey = privateKey.toString("hex"); | |
console.log({ | |
privateKey: backendPrivateKey, | |
publicKey: frontendPublicKey, | |
}); | |
// end setup | |
// frontend | |
let body = { hello: "world!" }; | |
console.log({ input: body }); | |
let str = JSON.stringify(body); | |
let encrypted = await encrypt( | |
Buffer.from(frontendPublicKey, "hex"), | |
Buffer.from(str) | |
); | |
let encryptedString: any = JSON.stringify( | |
Object.fromEntries( | |
Object.entries(encrypted).map(([key, value]: [string, Buffer]) => [ | |
key, | |
value.toString("hex"), | |
]) | |
) | |
); | |
const encoded = Buffer.from(encryptedString).toString("base64"); | |
// end frontend | |
// backend | |
const decoded = Buffer.from(encoded, "base64").toString("utf-8"); | |
const encryptedHex = JSON.parse(decoded); | |
let encrypted2: any = Object.fromEntries( | |
Object.entries(encryptedHex).map(([key, value]: [string, string]) => [ | |
key, | |
Buffer.from(value, "hex"), | |
]) | |
); | |
const decryptedBuffer = await decrypt( | |
Buffer.from(backendPrivateKey, "hex"), | |
encrypted2 | |
); | |
const decryptedString = decryptedBuffer.toString(); | |
const payload = JSON.parse(decryptedString); | |
console.log({ output: payload }); | |
// end backend |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment