Skip to content

Instantly share code, notes, and snippets.

@kevinvdburgt
Created December 27, 2024 08:44
Show Gist options
  • Select an option

  • Save kevinvdburgt/59dfdb4d7d279e8b07118f74ceba6ff5 to your computer and use it in GitHub Desktop.

Select an option

Save kevinvdburgt/59dfdb4d7d279e8b07118f74ceba6ff5 to your computer and use it in GitHub Desktop.
NodeJS asymmetric encryption
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()]);
},
};
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;
},
};
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