API Docs for: 1.0.8
Show:

File: client/lib/hkdf.js

  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. define(['sjcl'], function (sjcl) {
  5. 'use strict';
  6.  
  7. /**
  8. * hkdf - The HMAC-based Key Derivation Function
  9. * based on https://github.com/mozilla/node-hkdf
  10. *
  11. * @class hkdf
  12. * @param {bitArray} ikm Initial keying material
  13. * @param {bitArray} info Key derivation data
  14. * @param {bitArray} salt Salt
  15. * @param {integer} length Length of the derived key in bytes
  16. * @return promise object- It will resolve with `output` data
  17. */
  18. function hkdf(ikm, info, salt, length) {
  19.  
  20. var mac = new sjcl.misc.hmac(salt, sjcl.hash.sha256);
  21. mac.update(ikm);
  22.  
  23. // compute the PRK
  24. var prk = mac.digest();
  25.  
  26. // hash length is 32 because only sjcl.hash.sha256 is used at this moment
  27. var hashLength = 32;
  28. var num_blocks = Math.ceil(length / hashLength);
  29. var prev = sjcl.codec.hex.toBits('');
  30. var output = '';
  31.  
  32. for (var i = 0; i < num_blocks; i++) {
  33. var hmac = new sjcl.misc.hmac(prk, sjcl.hash.sha256);
  34.  
  35. var input = sjcl.bitArray.concat(
  36. sjcl.bitArray.concat(prev, info),
  37. sjcl.codec.utf8String.toBits((String.fromCharCode(i + 1)))
  38. );
  39.  
  40. hmac.update(input);
  41.  
  42. prev = hmac.digest();
  43. output += sjcl.codec.hex.fromBits(prev);
  44. }
  45.  
  46. var truncated = sjcl.bitArray.clamp(sjcl.codec.hex.toBits(output), length * 8);
  47.  
  48. return Promise.resolve(truncated);
  49. }
  50.  
  51. return hkdf;
  52.  
  53. });
  54.