All files / src/encryption sha2Hash.ts

47.06% Statements 8/17
25% Branches 2/8
60% Functions 3/5
47.06% Lines 8/17

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  1x                       236x       238x     238x                                                 1x 236x 236x     236x      
 
import { getCryptoLib } from './cryptoUtils'
 
type NodeCryptoCreateHash = typeof import('crypto').createHash
 
export interface Sha2Hash {
  digest(data: NodeJS.TypedArray, algorithm?: 'sha256' | 'sha512'): Promise<Buffer>;
}
 
class NodeCryptoSha2Hash {
  createHash: NodeCryptoCreateHash
 
  constructor(createHash: NodeCryptoCreateHash) {
    this.createHash = createHash
  }
 
  async digest(data: NodeJS.TypedArray, algorithm = 'sha256'): Promise<Buffer> {
    const result = this.createHash(algorithm)
      .update(data)
      .digest()
    return Promise.resolve(result)
  }
}
 
class WebCryptoSha2Hash implements Sha2Hash {
  subtleCrypto: SubtleCrypto
 
  constructor(subtleCrypto: SubtleCrypto) {
    this.subtleCrypto = subtleCrypto
  }
 
  async digest(data: NodeJS.TypedArray, algorithm = 'sha256'): Promise<Buffer> {
    let algo: string
    if (algorithm === 'sha256') {
      algo = 'SHA-256'
    } else if (algorithm === 'sha512') {
      algo = 'SHA-512'
    } else {
      throw new Error(`Unsupported hash algorithm ${algorithm}`)
    }
    const hash = await this.subtleCrypto.digest(algo, data)
    return Buffer.from(hash)
  }
}
 
export async function createSha2Hash(): Promise<Sha2Hash> {
  const cryptoLib = await getCryptoLib()
  Iif (cryptoLib.name === 'subtleCrypto') {
    return new WebCryptoSha2Hash(cryptoLib.lib)
  } else {
    return new NodeCryptoSha2Hash(cryptoLib.lib.createHash)
  }
}