All files / src/crypto-extras/crypto-aes node.ts

85.71% Statements 12/14
66.66% Branches 4/6
100% Functions 3/3
85.71% Lines 12/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 4442x           42x         59x 59x                 44x     44x 44x 44x                 15x     15x 15x 14x      
import { concatByteArrays } from 'micro-stacks/common';
import { AesCipher, CipherAlgorithm } from './types';
 
type NodeCryptoCreateCipher = typeof import('crypto').createCipheriv;
type NodeCryptoCreateDecipher = typeof import('crypto').createDecipheriv;
 
export class NodeCryptoAesCipher implements AesCipher {
  createCipher: NodeCryptoCreateCipher;
  createDecipher: NodeCryptoCreateDecipher;
 
  constructor(createCipher: NodeCryptoCreateCipher, createDecipher: NodeCryptoCreateDecipher) {
    this.createCipher = createCipher;
    this.createDecipher = createDecipher;
  }
 
  async encrypt(
    algorithm: CipherAlgorithm,
    key: Uint8Array,
    iv: Uint8Array,
    data: Uint8Array
  ): Promise<Uint8Array> {
    Iif (algorithm !== 'aes-128-cbc' && algorithm !== 'aes-256-cbc') {
      throw new Error(`Unsupported cipher algorithm "${algorithm}"`);
    }
    const cipher = this.createCipher(algorithm, key, iv);
    const result = concatByteArrays([cipher.update(data), cipher.final()]);
    return Promise.resolve(result);
  }
 
  async decrypt(
    algorithm: CipherAlgorithm,
    key: Uint8Array,
    iv: Uint8Array,
    data: Uint8Array
  ): Promise<Uint8Array> {
    Iif (algorithm !== 'aes-128-cbc' && algorithm !== 'aes-256-cbc') {
      throw new Error(`Unsupported cipher algorithm "${algorithm}"`);
    }
    const cipher = this.createDecipher(algorithm, key, iv);
    const result = concatByteArrays([cipher.update(data), cipher.final()]);
    return Promise.resolve(result);
  }
}