legacy.js 969 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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