Created
December 27, 2024 08:44
-
-
Save kevinvdburgt/59dfdb4d7d279e8b07118f74ceba6ff5 to your computer and use it in GitHub Desktop.
NodeJS 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
| import { createCipheriv, createDecipheriv, privateDecrypt, publicEncrypt, randomBytes } from 'node:crypto'; | |
| import { config } from '#infrastructure/config/config.js'; | |
| export const encryption = { | |
| encrypt: (buffer: Buffer) => { | |
| const key = randomBytes(32); | |
| const iv = randomBytes(16); | |
| const cipher = createCipheriv('aes-256-cbc', key, iv); | |
| const encryptedKey = publicEncrypt(config.encryption.publicKey, key); | |
| return Buffer.concat([encryptedKey, iv, cipher.update(buffer), cipher.final()]); | |
| }, | |
| decrypt: (buffer: Buffer) => { | |
| const encryptedKey = buffer.subarray(0, 512); | |
| const key = privateDecrypt(config.encryption.privateKey, encryptedKey); | |
| const iv = buffer.subarray(512, 528); | |
| const decipher = createDecipheriv('aes-256-cbc', key, iv); | |
| return Buffer.concat([decipher.update(buffer.subarray(528)), decipher.final()]); | |
| }, | |
| }; |
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
| import { z } from 'zod'; | |
| import { encryption } from '#infrastructure/encryption/encryption.js'; | |
| export const objectEncryption = { | |
| encrypt: (obj: object) => encryption.encrypt(Buffer.from(JSON.stringify(obj))), | |
| decrypt: <T extends object>(buffer: Buffer, schema?: z.ZodSchema<T>) => { | |
| const payload = JSON.parse(encryption.decrypt(buffer).toString()); | |
| if (schema) { | |
| return schema.parse(payload); | |
| } | |
| return payload as T; | |
| }, | |
| }; |
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
| import { encryption } from '#infrastructure/encryption/encryption.js'; | |
| export const stringEncryption = { | |
| encrypt: (str: string) => encryption.encrypt(Buffer.from(str)), | |
| decrypt: (buffer: Buffer) => encryption.decrypt(buffer).toString(), | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment