mode-cfb.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. ;(function (root, factory, undef) {
  2. if (typeof exports === "object") {
  3. // CommonJS
  4. module.exports = exports = factory(require("./core"), require("./cipher-core"));
  5. }
  6. else if (typeof define === "function" && define.amd) {
  7. // AMD
  8. define(["./core", "./cipher-core"], factory);
  9. }
  10. else {
  11. // Global (browser)
  12. factory(root.CryptoJS);
  13. }
  14. }(this, function (CryptoJS) {
  15. /**
  16. * Cipher Feedback block mode.
  17. */
  18. CryptoJS.mode.CFB = (function () {
  19. var CFB = CryptoJS.lib.BlockCipherMode.extend();
  20. CFB.Encryptor = CFB.extend({
  21. processBlock: function (words, offset) {
  22. // Shortcuts
  23. var cipher = this._cipher;
  24. var blockSize = cipher.blockSize;
  25. generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
  26. // Remember this block to use with next block
  27. this._prevBlock = words.slice(offset, offset + blockSize);
  28. }
  29. });
  30. CFB.Decryptor = CFB.extend({
  31. processBlock: function (words, offset) {
  32. // Shortcuts
  33. var cipher = this._cipher;
  34. var blockSize = cipher.blockSize;
  35. // Remember this block to use with next block
  36. var thisBlock = words.slice(offset, offset + blockSize);
  37. generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
  38. // This block becomes the previous block
  39. this._prevBlock = thisBlock;
  40. }
  41. });
  42. function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) {
  43. var keystream;
  44. // Shortcut
  45. var iv = this._iv;
  46. // Generate keystream
  47. if (iv) {
  48. keystream = iv.slice(0);
  49. // Remove IV for subsequent blocks
  50. this._iv = undefined;
  51. } else {
  52. keystream = this._prevBlock;
  53. }
  54. cipher.encryptBlock(keystream, 0);
  55. // Encrypt
  56. for (var i = 0; i < blockSize; i++) {
  57. words[offset + i] ^= keystream[i];
  58. }
  59. }
  60. return CFB;
  61. }());
  62. return CryptoJS.mode.CFB;
  63. }));