Blame view

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