All files / platform/packages/url-signer/src Hmac.js

92.86% Statements 13/14
83.33% Branches 5/6
100% Functions 4/4
92.86% Lines 13/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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61    1x 1x               48x             48x             22x             22x         22x       22x 22x       22x 22x       22x               1x  
'use strict';
 
const crypto = require('crypto');
const base64 = require('./Base64');
 
/**
 * A generic class for generating SHA-256 Hmac for verifying the value
 * integrity.
 */
class Hmac {
  constructor(key) {
    this.key = key;
  }
 
  /**
   * Generate the hmac
   */
  generate(value) {
    return base64.urlEncode(crypto.createHmac('sha256', this.key).update(value).digest());
  }
 
  /**
   * Compare raw value against an existing hmac
   */
  compare(value, existingHmac) {
    return this.safeEqual(this.generate(value), existingHmac);
  }
 
  /**
   * Generates a random string for a given size
   */
  safeEqual(value, comparisonValue) {
    Eif (typeof value === 'string' && typeof comparisonValue === 'string') {
      /**
       * The length of the main value to ensure that we compare equal strings
       * against each other to get a constant time.
       */
      const expectedLength = Buffer.byteLength(value);
      /**
       * Value A
       */
      const valueBuffer = Buffer.alloc(expectedLength, 0, 'utf-8');
      valueBuffer.write(value);
      /**
       * Value B
       */
      const comparisonValueBuffer = Buffer.alloc(expectedLength, 0, 'utf-8');
      comparisonValueBuffer.write(comparisonValue);
      /**
       * Ensure values are same and also have same length
       */
      return (
        crypto.timingSafeEqual(valueBuffer, comparisonValueBuffer) &&
        expectedLength === Buffer.byteLength(comparisonValue)
      );
    }
    return crypto.timingSafeEqual(Buffer.from(value), Buffer.from(comparisonValue));
  }
}
module.exports = Hmac;