index.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. var Transform = require('stream').Transform
  2. var inherits = require('inherits')
  3. var StringDecoder = require('string_decoder').StringDecoder
  4. module.exports = CipherBase
  5. inherits(CipherBase, Transform)
  6. function CipherBase (hashMode) {
  7. Transform.call(this)
  8. this.hashMode = typeof hashMode === 'string'
  9. if (this.hashMode) {
  10. this[hashMode] = this._finalOrDigest
  11. } else {
  12. this.final = this._finalOrDigest
  13. }
  14. this._decoder = null
  15. this._encoding = null
  16. }
  17. CipherBase.prototype.update = function (data, inputEnc, outputEnc) {
  18. if (typeof data === 'string') {
  19. data = new Buffer(data, inputEnc)
  20. }
  21. var outData = this._update(data)
  22. if (this.hashMode) {
  23. return this
  24. }
  25. if (outputEnc) {
  26. outData = this._toString(outData, outputEnc)
  27. }
  28. return outData
  29. }
  30. CipherBase.prototype.setAutoPadding = function () {}
  31. CipherBase.prototype.getAuthTag = function () {
  32. throw new Error('trying to get auth tag in unsupported state')
  33. }
  34. CipherBase.prototype.setAuthTag = function () {
  35. throw new Error('trying to set auth tag in unsupported state')
  36. }
  37. CipherBase.prototype.setAAD = function () {
  38. throw new Error('trying to set aad in unsupported state')
  39. }
  40. CipherBase.prototype._transform = function (data, _, next) {
  41. var err
  42. try {
  43. if (this.hashMode) {
  44. this._update(data)
  45. } else {
  46. this.push(this._update(data))
  47. }
  48. } catch (e) {
  49. err = e
  50. } finally {
  51. next(err)
  52. }
  53. }
  54. CipherBase.prototype._flush = function (done) {
  55. var err
  56. try {
  57. this.push(this._final())
  58. } catch (e) {
  59. err = e
  60. } finally {
  61. done(err)
  62. }
  63. }
  64. CipherBase.prototype._finalOrDigest = function (outputEnc) {
  65. var outData = this._final() || new Buffer('')
  66. if (outputEnc) {
  67. outData = this._toString(outData, outputEnc, true)
  68. }
  69. return outData
  70. }
  71. CipherBase.prototype._toString = function (value, enc, fin) {
  72. if (!this._decoder) {
  73. this._decoder = new StringDecoder(enc)
  74. this._encoding = enc
  75. }
  76. if (this._encoding !== enc) {
  77. throw new Error('can\'t switch encodings')
  78. }
  79. var out = this._decoder.write(value)
  80. if (fin) {
  81. out += this._decoder.end()
  82. }
  83. return out
  84. }