All files / src/apis/shared hmac.ts

100% Statements 14/14
100% Branches 4/4
100% Functions 2/2
100% Lines 11/11

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 506x 6x                               6x           6x 6x 6x   6x 6x     6x                     6x         5x    
import { hmac, timingSafeEqual, BinaryAlike } from "./platform/crypto";
import { hexToUint8Array, utf8ToUint8Array } from "./platform/decode";
 
export type HmacOptions = {
  algorithm?: string;
  key: BinaryAlike;
  data: BinaryAlike;
  digest: BinaryAlike;
};
 
/**
 *
 *
 * @export
 * @param {HmacOptions} options
 * @return {boolean}
 */
export function compareHmac({
  algorithm = "sha256",
  data,
  digest,
  key
}: HmacOptions) {
  if (typeof key === "string") key = utf8ToUint8Array(key);
  if (typeof data === "string") data = utf8ToUint8Array(data);
  if (typeof digest === "string") digest = hexToUint8Array(digest);
 
  const hash = hmac(algorithm, key, data);
  return timingSafeEqual(hash, digest);
}
 
const QIWI_JOINER = "|";
 
/**
 *
 *
 * @export
 * @param {string} key
 * @param {string} digest
 * @param {string[]} data
 * @return {boolean} boolean
 */
export function compareQiwiHmac(
  key: BinaryAlike,
  digest: BinaryAlike,
  data: string[]
): boolean {
  return compareHmac({ key, digest, data: data.join(QIWI_JOINER) });
}