mode-cfb.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. * Cipher Feedback block mode.
  15. */
  16. CryptoJS.mode.CFB = (function () {
  17. var CFB = CryptoJS.lib.BlockCipherMode.extend();
  18. CFB.Encryptor = CFB.extend({
  19. processBlock: function (words, offset) {
  20. // Shortcuts
  21. var cipher = this._cipher;
  22. var blockSize = cipher.blockSize;
  23. generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
  24. // Remember this block to use with next block
  25. this._prevBlock = words.slice(offset, offset + blockSize);
  26. }
  27. });
  28. CFB.Decryptor = CFB.extend({
  29. processBlock: function (words, offset) {
  30. // Shortcuts
  31. var cipher = this._cipher;
  32. var blockSize = cipher.blockSize;
  33. // Remember this block to use with next block
  34. var thisBlock = words.slice(offset, offset + blockSize);
  35. generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
  36. // This block becomes the previous block
  37. this._prevBlock = thisBlock;
  38. }
  39. });
  40. function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) {
  41. // Shortcut
  42. var iv = this._iv;
  43. // Generate keystream
  44. if (iv) {
  45. var keystream = iv.slice(0);
  46. // Remove IV for subsequent blocks
  47. this._iv = undefined;
  48. } else {
  49. var keystream = this._prevBlock;
  50. }
  51. cipher.encryptBlock(keystream, 0);
  52. // Encrypt
  53. for (var i = 0; i < blockSize; i++) {
  54. words[offset + i] ^= keystream[i];
  55. }
  56. }
  57. return CFB;
  58. }());
  59. return CryptoJS.mode.CFB;
  60. }));