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 () {
|
7 | Transform.call(this)
|
8 | this._decoder = null
|
9 | this._encoding = null
|
10 | }
|
11 | CipherBase.prototype.update = function (data, inputEnc, outputEnc) {
|
12 | if (typeof data === 'string') {
|
13 | data = new Buffer(data, inputEnc)
|
14 | }
|
15 | var outData = this._update(data)
|
16 | if (outputEnc) {
|
17 | outData = this._toString(outData, outputEnc)
|
18 | }
|
19 | return outData
|
20 | }
|
21 | CipherBase.prototype._transform = function (data, _, next) {
|
22 | this.push(this._update(data))
|
23 | next()
|
24 | }
|
25 | CipherBase.prototype._flush = function (next) {
|
26 | try {
|
27 | this.push(this._final())
|
28 | } catch(e) {
|
29 | return next(e)
|
30 | }
|
31 | next()
|
32 | }
|
33 | CipherBase.prototype.final = function (outputEnc) {
|
34 | var outData = this._final() || new Buffer('')
|
35 | if (outputEnc) {
|
36 | outData = this._toString(outData, outputEnc, true)
|
37 | }
|
38 | return outData
|
39 | }
|
40 |
|
41 | CipherBase.prototype._toString = function (value, enc, final) {
|
42 | if (!this._decoder) {
|
43 | this._decoder = new StringDecoder(enc)
|
44 | this._encoding = enc
|
45 | }
|
46 | if (this._encoding !== enc) {
|
47 | throw new Error('can\'t switch encodings')
|
48 | }
|
49 | var out = this._decoder.write(value)
|
50 | if (final) {
|
51 | out += this._decoder.end()
|
52 | }
|
53 | return out
|
54 | }
|