mode-ctr.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. ;(function (root, factory, undef) {
  2. if (typeof exports === "object") {
  3. // CommonJS
  4. module.exports = exports = factory(require("./core"), require("./cipher-core"));
  5. } else if (typeof define === "function" && define.amd) {
  6. // AMD
  7. define(["./core", "./cipher-core"], factory);
  8. } else {
  9. // Global (browser)
  10. factory(root.CryptoJS);
  11. }
  12. }(this, function (CryptoJS) {
  13. /**
  14. * Counter block mode.
  15. */
  16. CryptoJS.mode.CTR = (function () {
  17. var CTR = CryptoJS.lib.BlockCipherMode.extend();
  18. var Encryptor = CTR.Encryptor = CTR.extend({
  19. processBlock: function (words, offset) {
  20. // Shortcuts
  21. var cipher = this._cipher
  22. var blockSize = cipher.blockSize;
  23. var iv = this._iv;
  24. var counter = this._counter;
  25. // Generate keystream
  26. if (iv) {
  27. counter = this._counter = iv.slice(0);
  28. // Remove IV for subsequent blocks
  29. this._iv = undefined;
  30. }
  31. var keystream = counter.slice(0);
  32. cipher.encryptBlock(keystream, 0);
  33. // Increment counter
  34. counter[blockSize - 1] = (counter[blockSize - 1] + 1) | 0
  35. // Encrypt
  36. for (var i = 0; i < blockSize; i++) {
  37. words[offset + i] ^= keystream[i];
  38. }
  39. }
  40. });
  41. CTR.Decryptor = Encryptor;
  42. return CTR;
  43. }());
  44. return CryptoJS.mode.CTR;
  45. }));