All files / src/apis/shared crypto.ts

80.95% Statements 17/21
0% Branches 0/3
66.66% Functions 2/3
80.95% Lines 17/21

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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 683x 3x                       3x 1x       1x       1x       1x   1x 1x 1x 64x 64x   64x     1x                   3x                         3x         1x    
import { createHmac, randomBytes as _randomBytes } from "crypto";
import { getByIndex } from "./get";
 
export type BinaryAlike = string | Uint8Array;
 
/**
 *
 *
 * @export
 * @param {Uint8Array} array1
 * @param {Uint8Array} array2
 * @return {boolean} {boolean}
 */
export function timingSafeEqual(array1: Uint8Array, array2: Uint8Array): boolean {
  Iif (!(array1 instanceof Uint8Array)) {
    throw new TypeError("First argument must be an Uint8Array");
  }
 
  Iif (!(array2 instanceof Uint8Array)) {
    throw new TypeError("Second argument must be an Uint8Array");
  }
 
  Iif (array1.length !== array2.length) {
    throw new TypeError("Input arrays must have the same length");
  }
 
  const length = array1.length;
 
  let out = 0;
  let index = -1;
  while (++index < length) {
    const value1 = getByIndex(array1, index) as number;
    const value2 = getByIndex(array2, index) as number;
 
    out |= value1 ^ value2;
  }
 
  return out === 0;
}
 
/**
 *
 *
 * @export
 * @param {number} size
 * @return {Uint8Array}  {Uint8Array}
 */
export function randomBytes(size: number): Uint8Array {
  return _randomBytes(size);
}
 
/**
 *
 *
 * @export
 * @param {string} algorithm
 * @param {Uint8Array} key
 * @param {Uint8Array} data
 * @return {Uint8Array}  {Uint8Array}
 */
export function hmac(
  algorithm: string,
  key: Uint8Array,
  data: Uint8Array
): Uint8Array {
  return createHmac(algorithm, key).update(data).digest();
}