Skip to content

Instantly share code, notes, and snippets.

@jenyayel
Last active January 15, 2021 21:32
Show Gist options
  • Save jenyayel/e91b431f2fc4af5c690dcde492d9d1a7 to your computer and use it in GitHub Desktop.
Save jenyayel/e91b431f2fc4af5c690dcde492d9d1a7 to your computer and use it in GitHub Desktop.
Symmetric encryption for nodejs
import * as crypto from 'crypto';
import { CipherGCMTypes } from 'crypto';
// defaults source: https://stackoverflow.com/a/53573115/2307459
const BLOCK_CIPHER: CipherGCMTypes = 'aes-256-gcm';
const AUTH_TAG_BYTE_LEN = 16;
const IV_BYTE_LEN = 12;
const KEY_BYTE_LEN = 32;
export class SymmetricCrypto {
private readonly symmetricKey: Buffer;
constructor(symmetricKey: string) {
this.symmetricKey = Buffer.from(symmetricKey);
if (this.symmetricKey.length !== KEY_BYTE_LEN) {
throw new Error(`Key length must be ${KEY_BYTE_LEN}`);
}
}
public encrypt = (message: string) => {
const iv = crypto.randomBytes(IV_BYTE_LEN);
const cipher = crypto.createCipheriv(
BLOCK_CIPHER,
this.symmetricKey,
iv,
{ authTagLength: AUTH_TAG_BYTE_LEN });
const encryptedMessage = cipher.update(Buffer.from(message));
return Buffer
.concat([
iv,
Buffer.concat([encryptedMessage, cipher.final()]),
cipher.getAuthTag()])
.toString('base64');
}
public decrypt = (payload: string) => {
const payloadBuffer = Buffer.from(payload, 'base64');
const authTag = payloadBuffer.slice(-AUTH_TAG_BYTE_LEN);
const iv = payloadBuffer.slice(0, IV_BYTE_LEN);
const encryptedMessage = payloadBuffer.slice(IV_BYTE_LEN, -AUTH_TAG_BYTE_LEN);
const decipher = crypto.createDecipheriv(
BLOCK_CIPHER,
this.symmetricKey,
iv,
{ authTagLength: AUTH_TAG_BYTE_LEN });
decipher.setAuthTag(authTag);
const message = decipher.update(encryptedMessage);
return Buffer
.concat([message, decipher.final()])
.toString('utf8');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment