You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

57 lines
1.6 KiB

4 years ago
  1. /**
  2. * Javascript implementation of mask generation function MGF1.
  3. *
  4. * @author Stefan Siegl
  5. * @author Dave Longley
  6. *
  7. * Copyright (c) 2012 Stefan Siegl <stesie@brokenpipe.de>
  8. * Copyright (c) 2014 Digital Bazaar, Inc.
  9. */
  10. var forge = require('./forge');
  11. require('./util');
  12. forge.mgf = forge.mgf || {};
  13. var mgf1 = module.exports = forge.mgf.mgf1 = forge.mgf1 = forge.mgf1 || {};
  14. /**
  15. * Creates a MGF1 mask generation function object.
  16. *
  17. * @param md the message digest API to use (eg: forge.md.sha1.create()).
  18. *
  19. * @return a mask generation function object.
  20. */
  21. mgf1.create = function(md) {
  22. var mgf = {
  23. /**
  24. * Generate mask of specified length.
  25. *
  26. * @param {String} seed The seed for mask generation.
  27. * @param maskLen Number of bytes to generate.
  28. * @return {String} The generated mask.
  29. */
  30. generate: function(seed, maskLen) {
  31. /* 2. Let T be the empty octet string. */
  32. var t = new forge.util.ByteBuffer();
  33. /* 3. For counter from 0 to ceil(maskLen / hLen), do the following: */
  34. var len = Math.ceil(maskLen / md.digestLength);
  35. for(var i = 0; i < len; i++) {
  36. /* a. Convert counter to an octet string C of length 4 octets */
  37. var c = new forge.util.ByteBuffer();
  38. c.putInt32(i);
  39. /* b. Concatenate the hash of the seed mgfSeed and C to the octet
  40. * string T: */
  41. md.start();
  42. md.update(seed + c.getBytes());
  43. t.putBuffer(md.digest());
  44. }
  45. /* Output the leading maskLen octets of T as the octet string mask. */
  46. t.truncate(t.length() - maskLen);
  47. return t.getBytes();
  48. }
  49. };
  50. return mgf;
  51. };