HMAC.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. (function () {
  2. var C = typeof window === 'undefined' ? require('./Crypto').Crypto : window.Crypto;
  3. // Shortcuts
  4. var util = C.util;
  5. var charenc = C.charenc;
  6. var UTF8 = charenc.UTF8;
  7. var Binary = charenc.Binary;
  8. C.HMAC = function (hasher, message, key, options) {
  9. // Convert to byte arrays
  10. if (message.constructor == String) {
  11. message = UTF8.stringToBytes(message);
  12. }
  13. if (key.constructor == String) {
  14. key = UTF8.stringToBytes(key);
  15. }
  16. /* else, assume byte arrays already */
  17. // Allow arbitrary length keys
  18. if (key.length > hasher._blocksize * 4) {
  19. key = hasher(key, {
  20. asBytes: true
  21. });
  22. }
  23. // XOR keys with pad constants
  24. var okey = key.slice(0);
  25. var ikey = key.slice(0);
  26. for (var i = 0; i < hasher._blocksize * 4; i++) {
  27. okey[i] ^= 92;
  28. ikey[i] ^= 54;
  29. }
  30. var hmacbytes = hasher(
  31. okey.concat(
  32. hasher(ikey.concat(message), {
  33. asBytes: true
  34. })
  35. ),
  36. {
  37. asBytes: true
  38. }
  39. );
  40. return options && options.asBytes ? hmacbytes : options && options.asString ? Binary.bytesToString(hmacbytes) : util.bytesToHex(hmacbytes);
  41. };
  42. })();