Projekt

Obecné

Profil

Stáhnout (2.17 KB) Statistiky
| Větev: | Revize:
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

    
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
  if (this._final) {
15
    this.__final = this._final
16
    this._final = null
17
  }
18
  this._decoder = null
19
  this._encoding = null
20
}
21
inherits(CipherBase, Transform)
22

    
23
CipherBase.prototype.update = function (data, inputEnc, outputEnc) {
24
  if (typeof data === 'string') {
25
    data = Buffer.from(data, inputEnc)
26
  }
27

    
28
  var outData = this._update(data)
29
  if (this.hashMode) return this
30

    
31
  if (outputEnc) {
32
    outData = this._toString(outData, outputEnc)
33
  }
34

    
35
  return outData
36
}
37

    
38
CipherBase.prototype.setAutoPadding = function () {}
39
CipherBase.prototype.getAuthTag = function () {
40
  throw new Error('trying to get auth tag in unsupported state')
41
}
42

    
43
CipherBase.prototype.setAuthTag = function () {
44
  throw new Error('trying to set auth tag in unsupported state')
45
}
46

    
47
CipherBase.prototype.setAAD = function () {
48
  throw new Error('trying to set aad in unsupported state')
49
}
50

    
51
CipherBase.prototype._transform = function (data, _, next) {
52
  var err
53
  try {
54
    if (this.hashMode) {
55
      this._update(data)
56
    } else {
57
      this.push(this._update(data))
58
    }
59
  } catch (e) {
60
    err = e
61
  } finally {
62
    next(err)
63
  }
64
}
65
CipherBase.prototype._flush = function (done) {
66
  var err
67
  try {
68
    this.push(this.__final())
69
  } catch (e) {
70
    err = e
71
  }
72

    
73
  done(err)
74
}
75
CipherBase.prototype._finalOrDigest = function (outputEnc) {
76
  var outData = this.__final() || Buffer.alloc(0)
77
  if (outputEnc) {
78
    outData = this._toString(outData, outputEnc, true)
79
  }
80
  return outData
81
}
82

    
83
CipherBase.prototype._toString = function (value, enc, fin) {
84
  if (!this._decoder) {
85
    this._decoder = new StringDecoder(enc)
86
    this._encoding = enc
87
  }
88

    
89
  if (this._encoding !== enc) throw new Error('can\'t switch encodings')
90

    
91
  var out = this._decoder.write(value)
92
  if (fin) {
93
    out += this._decoder.end()
94
  }
95

    
96
  return out
97
}
98

    
99
module.exports = CipherBase
(6-6/8)