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.

65 lines
1.4 KiB

4 years ago
  1. 'use strict';
  2. var assert = require('minimalistic-assert');
  3. var inherits = require('inherits');
  4. var proto = {};
  5. function CBCState(iv) {
  6. assert.equal(iv.length, 8, 'Invalid IV length');
  7. this.iv = new Array(8);
  8. for (var i = 0; i < this.iv.length; i++)
  9. this.iv[i] = iv[i];
  10. }
  11. function instantiate(Base) {
  12. function CBC(options) {
  13. Base.call(this, options);
  14. this._cbcInit();
  15. }
  16. inherits(CBC, Base);
  17. var keys = Object.keys(proto);
  18. for (var i = 0; i < keys.length; i++) {
  19. var key = keys[i];
  20. CBC.prototype[key] = proto[key];
  21. }
  22. CBC.create = function create(options) {
  23. return new CBC(options);
  24. };
  25. return CBC;
  26. }
  27. exports.instantiate = instantiate;
  28. proto._cbcInit = function _cbcInit() {
  29. var state = new CBCState(this.options.iv);
  30. this._cbcState = state;
  31. };
  32. proto._update = function _update(inp, inOff, out, outOff) {
  33. var state = this._cbcState;
  34. var superProto = this.constructor.super_.prototype;
  35. var iv = state.iv;
  36. if (this.type === 'encrypt') {
  37. for (var i = 0; i < this.blockSize; i++)
  38. iv[i] ^= inp[inOff + i];
  39. superProto._update.call(this, iv, 0, out, outOff);
  40. for (var i = 0; i < this.blockSize; i++)
  41. iv[i] = out[outOff + i];
  42. } else {
  43. superProto._update.call(this, inp, inOff, out, outOff);
  44. for (var i = 0; i < this.blockSize; i++)
  45. out[outOff + i] ^= iv[i];
  46. for (var i = 0; i < this.blockSize; i++)
  47. iv[i] = inp[inOff + i];
  48. }
  49. };