HMAC.js 1.0 KB

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