All files / utils subtle-crypto.ts

100% Statements 7/7
100% Branches 4/4
100% Functions 2/2
100% Lines 5/5

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              16x   7x     7x     7x     260x    
export type Algorithms = 'SHA-1' | 'SHA-256' | 'SHA-384' | 'SHA-512';
 
export async function hash(
  algorithm?: Algorithms,
  message?: string,
  defaultValue?: string
): Promise<string | undefined> {
  if (!algorithm || !message) return defaultValue;
 
  const msgBuffer = new TextEncoder().encode(message);
 
  // hash the message
  const hashBuffer = await crypto.subtle.digest(algorithm, msgBuffer);
 
  // convert ArrayBuffer to Array
  const hashArray = Array.from(new Uint8Array(hashBuffer));
 
  // convert bytes to hex string
  return hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');
}