mode-ctr-gladman.js 2.0 KB

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