mode-ctr-gladman.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. /** @preserve
  14. * Counter block mode compatible with Dr Brian Gladman fileenc.c
  15. * derived from CryptoJS.mode.CTR
  16. * Jan Hruby jhruby.web@gmail.com
  17. */
  18. CryptoJS.mode.CTRGladman = (function () {
  19. var CTRGladman = CryptoJS.lib.BlockCipherMode.extend();
  20. function incWord(word) {
  21. if (((word >> 24) & 0xff) === 0xff) { //overflow
  22. var b1 = (word >> 16) & 0xff;
  23. var b2 = (word >> 8) & 0xff;
  24. var b3 = word & 0xff;
  25. if (b1 === 0xff) // overflow b1
  26. {
  27. b1 = 0;
  28. if (b2 === 0xff) {
  29. b2 = 0;
  30. if (b3 === 0xff) {
  31. b3 = 0;
  32. } else {
  33. ++b3;
  34. }
  35. } else {
  36. ++b2;
  37. }
  38. } else {
  39. ++b1;
  40. }
  41. word = 0;
  42. word += (b1 << 16);
  43. word += (b2 << 8);
  44. word += b3;
  45. } else {
  46. word += (0x01 << 24);
  47. }
  48. return word;
  49. }
  50. function incCounter(counter) {
  51. if ((counter[0] = incWord(counter[0])) === 0) {
  52. // encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8
  53. counter[1] = incWord(counter[1]);
  54. }
  55. return counter;
  56. }
  57. var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({
  58. processBlock: function (words, offset) {
  59. // Shortcuts
  60. var cipher = this._cipher
  61. var blockSize = cipher.blockSize;
  62. var iv = this._iv;
  63. var counter = this._counter;
  64. // Generate keystream
  65. if (iv) {
  66. counter = this._counter = iv.slice(0);
  67. // Remove IV for subsequent blocks
  68. this._iv = undefined;
  69. }
  70. incCounter(counter);
  71. var keystream = counter.slice(0);
  72. cipher.encryptBlock(keystream, 0);
  73. // Encrypt
  74. for (var i = 0; i < blockSize; i++) {
  75. words[offset + i] ^= keystream[i];
  76. }
  77. }
  78. });
  79. CTRGladman.Decryptor = Encryptor;
  80. return CTRGladman;
  81. }());
  82. return CryptoJS.mode.CTRGladman;
  83. }));