index.js 2.2 KB

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