Skip to content

Instantly share code, notes, and snippets.

@peatiscoding
Last active July 18, 2020 08:46
Show Gist options
  • Save peatiscoding/e859143017f0ebfc4c9785e337e15bf1 to your computer and use it in GitHub Desktop.
Save peatiscoding/e859143017f0ebfc4c9785e337e15bf1 to your computer and use it in GitHub Desktop.
Example usage of AES128 to encrypt/decrypt message with GCM
import { createDecipheriv, randomBytes, CipherGCM, HexBase64BinaryEncoding, createCipheriv, Decipher, pbkdf2Sync } from 'crypto'
const gcmTagSize = 16
const nonceSize = 12
export default class Tunnel {
private getDecipher: (iv: Buffer, authTag: Buffer) => Decipher
private getCipher: (iv: Buffer) => CipherGCM
constructor(key: string, salt: string, public encryptedEncoding: HexBase64BinaryEncoding) {
const derivedKey = pbkdf2Sync(key, salt, 2000, 128 / 8, 'sha512')
this.getDecipher = (iv: Buffer, authTag: Buffer) => {
return createDecipheriv('aes-128-gcm', derivedKey, iv).setAuthTag(authTag)
}
this.getCipher = (iv: Buffer) => {
return createCipheriv('aes-128-gcm', derivedKey, iv)
}
}
decrypt(encrypted: string): string {
const buffer = Buffer.from(encrypted, this.encryptedEncoding)
const nonce = buffer.slice(0, nonceSize)
const cipherText = buffer.slice(nonceSize, buffer.length - gcmTagSize)
const tag = buffer.slice(buffer.length - gcmTagSize)
const decipher = this.getDecipher(nonce, tag)
let out = decipher.update(cipherText, 'binary', 'utf8')
out += decipher.final('utf8')
return out
}
encrypt(message: string): string {
const nonce = randomBytes(96/8)
const cipher = this.getCipher(nonce)
const encrypted = Buffer.concat([
nonce,
cipher.update(message, 'utf8'),
cipher.final(),
cipher.getAuthTag()
])
return encrypted.toString(this.encryptedEncoding)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment