You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. 'use strict'
  2. var inherits = require('inherits')
  3. var Buffer = require('safe-buffer').Buffer
  4. var Base = require('cipher-base')
  5. var ZEROS = Buffer.alloc(128)
  6. var blocksize = 64
  7. function Hmac (alg, key) {
  8. Base.call(this, 'digest')
  9. if (typeof key === 'string') {
  10. key = Buffer.from(key)
  11. }
  12. this._alg = alg
  13. this._key = key
  14. if (key.length > blocksize) {
  15. key = alg(key)
  16. } else if (key.length < blocksize) {
  17. key = Buffer.concat([key, ZEROS], blocksize)
  18. }
  19. var ipad = this._ipad = Buffer.allocUnsafe(blocksize)
  20. var opad = this._opad = Buffer.allocUnsafe(blocksize)
  21. for (var i = 0; i < blocksize; i++) {
  22. ipad[i] = key[i] ^ 0x36
  23. opad[i] = key[i] ^ 0x5C
  24. }
  25. this._hash = [ipad]
  26. }
  27. inherits(Hmac, Base)
  28. Hmac.prototype._update = function (data) {
  29. this._hash.push(data)
  30. }
  31. Hmac.prototype._final = function () {
  32. var h = this._alg(Buffer.concat(this._hash))
  33. return this._alg(Buffer.concat([this._opad, h]))
  34. }
  35. module.exports = Hmac