setup/factors/hmacsha1.js

  1. /**
  2. * @file MFKDF HMAC-SHA1 Factor Setup
  3. * @copyright Multifactor 2022 All Rights Reserved
  4. *
  5. * @description
  6. * Setup an HMAC-SHA1 challenge-response factor for multi-factor key derivation
  7. *
  8. * @author Vivek Nair (https://nair.me) <vivek@nair.me>
  9. */
  10. const defaults = require('../../defaults')
  11. const crypto = require('crypto')
  12. const xor = require('buffer-xor')
  13. /**
  14. * Setup a YubiKey-compatible MFKDF HMAC-SHA1 challenge-response factor
  15. *
  16. * @example
  17. * // setup key with hmacsha1 factor
  18. * const setup = await mfkdf.setup.key([
  19. * await mfkdf.setup.factors.hmacsha1()
  20. * ], {size: 8})
  21. *
  22. * // calculate response; could be done using hardware device
  23. * const secret = setup.outputs.hmacsha1.secret
  24. * const challenge = Buffer.from(setup.policy.factors[0].params.challenge, 'hex')
  25. * const response = crypto.createHmac('sha1', secret).update(challenge).digest()
  26. *
  27. * // derive key with hmacsha1 factor
  28. * const derive = await mfkdf.derive.key(setup.policy, {
  29. * hmacsha1: mfkdf.derive.factors.hmacsha1(response)
  30. * })
  31. *
  32. * setup.key.toString('hex') // -> 01d0c7236adf2516
  33. * derive.key.toString('hex') // -> 01d0c7236adf2516
  34. *
  35. * @param {Object} [options] - Configuration options
  36. * @param {string} [options.id='hmacsha1'] - Unique identifier for this factor
  37. * @param {Buffer} [options.secret] - HMAC secret to use; randomly generated by default
  38. * @returns {MFKDFFactor} MFKDF factor information
  39. * @author Vivek Nair (https://nair.me) <vivek@nair.me>
  40. * @since 0.21.0
  41. * @async
  42. * @memberof setup.factors
  43. */
  44. async function hmacsha1 (options) {
  45. options = Object.assign(Object.assign({}, defaults.hmacsha1), options)
  46. if (typeof options.id !== 'string') throw new TypeError('id must be a string')
  47. if (options.id.length === 0) throw new RangeError('id cannot be empty')
  48. if (typeof options.secret === 'undefined') options.secret = crypto.randomBytes(20)
  49. if (!Buffer.isBuffer(options.secret)) throw new TypeError('secret must be a buffer')
  50. if (Buffer.byteLength(options.secret) !== 20) throw new RangeError('secret must be 20 bytes')
  51. return {
  52. type: 'hmacsha1',
  53. id: options.id,
  54. data: options.secret,
  55. entropy: 160,
  56. params: async ({ key }) => {
  57. const challenge = crypto.randomBytes(64)
  58. const response = crypto.createHmac('sha1', options.secret).update(challenge).digest()
  59. const pad = xor(response.subarray(0, 20), options.secret)
  60. return {
  61. challenge: challenge.toString('hex'),
  62. pad: pad.toString('hex')
  63. }
  64. },
  65. output: async () => {
  66. return { secret: options.secret }
  67. }
  68. }
  69. }
  70. module.exports.hmacsha1 = hmacsha1