A library for multi-key reversible encryption
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 

35 lines
1.2 KiB

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<EncodedValue> {
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<DecodedValue> {
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()
}
}