mode-ctr.js 867 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. /**
  2. * Counter block mode.
  3. */
  4. import {
  5. BlockCipherMode,
  6. } from './cipher-core.js';
  7. export class CTR extends BlockCipherMode {
  8. }
  9. CTR.Encryptor = class extends CTR {
  10. processBlock(words, offset) {
  11. const _words = words;
  12. // Shortcuts
  13. const cipher = this._cipher;
  14. const { blockSize } = cipher;
  15. const iv = this._iv;
  16. let counter = this._counter;
  17. // Generate keystream
  18. if (iv) {
  19. this._counter = iv.slice(0);
  20. counter = this._counter;
  21. // Remove IV for subsequent blocks
  22. this._iv = undefined;
  23. }
  24. const keystream = counter.slice(0);
  25. cipher.encryptBlock(keystream, 0);
  26. // Increment counter
  27. counter[blockSize - 1] = (counter[blockSize - 1] + 1) | 0;
  28. // Encrypt
  29. for (let i = 0; i < blockSize; i += 1) {
  30. _words[offset + i] ^= keystream[i];
  31. }
  32. }
  33. };
  34. CTR.Decryptor = CTR.Encryptor;