hmac.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. /** @fileOverview HMAC implementation.
  2. *
  3. * @author Emily Stark
  4. * @author Mike Hamburg
  5. * @author Dan Boneh
  6. */
  7. /** HMAC with the specified hash function.
  8. * @constructor
  9. * @param {bitArray} key the key for HMAC.
  10. * @param {Object} [hash=sjcl.hash.sha256] The hash function to use.
  11. */
  12. sjcl.misc.hmac = function (key, Hash) {
  13. this._hash = Hash = Hash || sjcl.hash.sha256;
  14. var exKey = [[],[]], i,
  15. bs = Hash.prototype.blockSize / 32;
  16. this._baseHash = [new Hash(), new Hash()];
  17. if (key.length > bs) {
  18. key = Hash.hash(key);
  19. }
  20. for (i=0; i<bs; i++) {
  21. exKey[0][i] = key[i]^0x36363636;
  22. exKey[1][i] = key[i]^0x5C5C5C5C;
  23. }
  24. this._baseHash[0].update(exKey[0]);
  25. this._baseHash[1].update(exKey[1]);
  26. };
  27. /** HMAC with the specified hash function. Also called encrypt since it's a prf.
  28. * @param {bitArray|String} data The data to mac.
  29. * @param {Codec} [encoding] the encoding function to use.
  30. */
  31. sjcl.misc.hmac.prototype.encrypt = sjcl.misc.hmac.prototype.mac = function (data, encoding) {
  32. var w = new (this._hash)(this._baseHash[0]).update(data, encoding).finalize();
  33. return new (this._hash)(this._baseHash[1]).update(w).finalize();
  34. };