hmac.js 840 B

12345678910111213141516171819202122232425262728293031323334
  1. const Crypto = require('./crypto.js');
  2. (function(){
  3. // Shortcut
  4. var util = Crypto.util;
  5. Crypto.HMAC = function (hasher, message, key, options) {
  6. // Allow arbitrary length keys
  7. key = key.length > hasher._blocksize * 4 ?
  8. hasher(key, { asBytes: true }) :
  9. util.stringToBytes(key);
  10. // XOR keys with pad constants
  11. var okey = key,
  12. ikey = key.slice(0);
  13. for (var i = 0; i < hasher._blocksize * 4; i++) {
  14. okey[i] ^= 0x5C;
  15. ikey[i] ^= 0x36;
  16. }
  17. var hmacbytes = hasher(util.bytesToString(okey) +
  18. hasher(util.bytesToString(ikey) + message, { asString: true }),
  19. { asBytes: true });
  20. return options && options.asBytes ? hmacbytes :
  21. options && options.asString ? util.bytesToString(hmacbytes) :
  22. util.bytesToHex(hmacbytes);
  23. };
  24. })();
  25. module.exports = Crypto;