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.

index.js 2.2KB

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