hash.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. var Buffer = require('safe-buffer').Buffer
  2. // prototype class for hash functions
  3. function Hash (blockSize, finalSize) {
  4. this._block = Buffer.alloc(blockSize)
  5. this._finalSize = finalSize
  6. this._blockSize = blockSize
  7. this._len = 0
  8. }
  9. Hash.prototype.update = function (data, enc) {
  10. if (typeof data === 'string') {
  11. enc = enc || 'utf8'
  12. data = Buffer.from(data, enc)
  13. }
  14. var block = this._block
  15. var blockSize = this._blockSize
  16. var length = data.length
  17. var accum = this._len
  18. for (var offset = 0; offset < length;) {
  19. var assigned = accum % blockSize
  20. var remainder = Math.min(length - offset, blockSize - assigned)
  21. for (var i = 0; i < remainder; i++) {
  22. block[assigned + i] = data[offset + i]
  23. }
  24. accum += remainder
  25. offset += remainder
  26. if ((accum % blockSize) === 0) {
  27. this._update(block)
  28. }
  29. }
  30. this._len += length
  31. return this
  32. }
  33. Hash.prototype.digest = function (enc) {
  34. var rem = this._len % this._blockSize
  35. this._block[rem] = 0x80
  36. // zero (rem + 1) trailing bits, where (rem + 1) is the smallest
  37. // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize
  38. this._block.fill(0, rem + 1)
  39. if (rem >= this._finalSize) {
  40. this._update(this._block)
  41. this._block.fill(0)
  42. }
  43. var bits = this._len * 8
  44. // uint32
  45. if (bits <= 0xffffffff) {
  46. this._block.writeUInt32BE(bits, this._blockSize - 4)
  47. // uint64
  48. } else {
  49. var lowBits = (bits & 0xffffffff) >>> 0
  50. var highBits = (bits - lowBits) / 0x100000000
  51. this._block.writeUInt32BE(highBits, this._blockSize - 8)
  52. this._block.writeUInt32BE(lowBits, this._blockSize - 4)
  53. }
  54. this._update(this._block)
  55. var hash = this._hash()
  56. return enc ? hash.toString(enc) : hash
  57. }
  58. Hash.prototype._update = function () {
  59. throw new Error('_update must be implemented by subclass')
  60. }
  61. module.exports = Hash