hmac.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. 'use strict';
  2. var utils = require('./utils');
  3. var assert = require('minimalistic-assert');
  4. function Hmac(hash, key, enc) {
  5. if (!(this instanceof Hmac))
  6. return new Hmac(hash, key, enc);
  7. this.Hash = hash;
  8. this.blockSize = hash.blockSize / 8;
  9. this.outSize = hash.outSize / 8;
  10. this.inner = null;
  11. this.outer = null;
  12. this._init(utils.toArray(key, enc));
  13. }
  14. module.exports = Hmac;
  15. Hmac.prototype._init = function init(key) {
  16. // Shorten key, if needed
  17. if (key.length > this.blockSize)
  18. key = new this.Hash().update(key).digest();
  19. assert(key.length <= this.blockSize);
  20. // Add padding to key
  21. for (var i = key.length; i < this.blockSize; i++)
  22. key.push(0);
  23. for (i = 0; i < key.length; i++)
  24. key[i] ^= 0x36;
  25. this.inner = new this.Hash().update(key);
  26. // 0x36 ^ 0x5c = 0x6a
  27. for (i = 0; i < key.length; i++)
  28. key[i] ^= 0x6a;
  29. this.outer = new this.Hash().update(key);
  30. };
  31. Hmac.prototype.update = function update(msg, enc) {
  32. this.inner.update(msg, enc);
  33. return this;
  34. };
  35. Hmac.prototype.digest = function digest(enc) {
  36. this.outer.update(this.inner.digest());
  37. return this.outer.digest(enc);
  38. };