import {Cryptor} from './Cryptor' import {Awaitable, DecodedValue, EncodedValue} from '../types' import * as crypto from 'crypto' import { Buffer } from 'buffer' /** * AES 256 implementation of a Cryptor. */ export class AES256Cryptor extends Cryptor { encode(value: DecodedValue): Awaitable { const hash = crypto.createHash('sha256') hash.update(this.key) const vector = crypto.randomBytes(16) const cipher = crypto.createCipheriv('aes-256-ctr', hash.digest(), vector) const input = Buffer.from(value) const cipherText = cipher.update(input) const encoded = Buffer.concat([vector, cipherText, cipher.final()]) return encoded.toString('base64') } decode(payload: EncodedValue): Awaitable { const hash = crypto.createHash('sha256') hash.update(this.key) const input = Buffer.from(payload, 'base64') const vector = input.slice(0, 16) const decipher = crypto.createDecipheriv('aes-256-ctr', hash.digest(), vector) const cipherText = input.slice(16) const decoded = Buffer.concat([decipher.update(cipherText), decipher.final()]) return decoded.toString() } }