mode-cfb.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. // Shortcut
  44. var iv = this._iv;
  45. // Generate keystream
  46. if (iv) {
  47. var keystream = iv.slice(0);
  48. // Remove IV for subsequent blocks
  49. this._iv = undefined;
  50. } else {
  51. var keystream = this._prevBlock;
  52. }
  53. cipher.encryptBlock(keystream, 0);
  54. // Encrypt
  55. for (var i = 0; i < blockSize; i++) {
  56. words[offset + i] ^= keystream[i];
  57. }
  58. }
  59. return CFB;
  60. }());
  61. return CryptoJS.mode.CFB;
  62. }));