index.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. 'use strict'
  2. var Transform = require('stream').Transform
  3. var inherits = require('inherits')
  4. function HashBase (blockSize) {
  5. Transform.call(this)
  6. this._block = new Buffer(blockSize)
  7. this._blockSize = blockSize
  8. this._blockOffset = 0
  9. this._length = [0, 0, 0, 0]
  10. this._finalized = false
  11. }
  12. inherits(HashBase, Transform)
  13. HashBase.prototype._transform = function (chunk, encoding, callback) {
  14. var error = null
  15. try {
  16. if (encoding !== 'buffer') chunk = new Buffer(chunk, encoding)
  17. this.update(chunk)
  18. } catch (err) {
  19. error = err
  20. }
  21. callback(error)
  22. }
  23. HashBase.prototype._flush = function (callback) {
  24. var error = null
  25. try {
  26. this.push(this._digest())
  27. } catch (err) {
  28. error = err
  29. }
  30. callback(error)
  31. }
  32. HashBase.prototype.update = function (data, encoding) {
  33. if (!Buffer.isBuffer(data) && typeof data !== 'string') throw new TypeError('Data must be a string or a buffer')
  34. if (this._finalized) throw new Error('Digest already called')
  35. if (!Buffer.isBuffer(data)) data = new Buffer(data, encoding || 'binary')
  36. // consume data
  37. var block = this._block
  38. var offset = 0
  39. while (this._blockOffset + data.length - offset >= this._blockSize) {
  40. for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]
  41. this._update()
  42. this._blockOffset = 0
  43. }
  44. while (offset < data.length) block[this._blockOffset++] = data[offset++]
  45. // update length
  46. for (var j = 0, carry = data.length * 8; carry > 0; ++j) {
  47. this._length[j] += carry
  48. carry = (this._length[j] / 0x0100000000) | 0
  49. if (carry > 0) this._length[j] -= 0x0100000000 * carry
  50. }
  51. return this
  52. }
  53. HashBase.prototype._update = function (data) {
  54. throw new Error('_update is not implemented')
  55. }
  56. HashBase.prototype.digest = function (encoding) {
  57. if (this._finalized) throw new Error('Digest already called')
  58. this._finalized = true
  59. var digest = this._digest()
  60. if (encoding !== undefined) digest = digest.toString(encoding)
  61. return digest
  62. }
  63. HashBase.prototype._digest = function () {
  64. throw new Error('_digest is not implemented')
  65. }
  66. module.exports = HashBase