rc4.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. import {
  2. StreamCipher,
  3. } from './cipher-core.js';
  4. function generateKeystreamWord() {
  5. // Shortcuts
  6. const S = this._S;
  7. let i = this._i;
  8. let j = this._j;
  9. // Generate keystream word
  10. let keystreamWord = 0;
  11. for (let n = 0; n < 4; n += 1) {
  12. i = (i + 1) % 256;
  13. j = (j + S[i]) % 256;
  14. // Swap
  15. const t = S[i];
  16. S[i] = S[j];
  17. S[j] = t;
  18. keystreamWord |= S[(S[i] + S[j]) % 256] << (24 - n * 8);
  19. }
  20. // Update counters
  21. this._i = i;
  22. this._j = j;
  23. return keystreamWord;
  24. }
  25. /**
  26. * RC4 stream cipher algorithm.
  27. */
  28. export class RC4Algo extends StreamCipher {
  29. _doReset() {
  30. // Shortcuts
  31. const key = this._key;
  32. const keyWords = key.words;
  33. const keySigBytes = key.sigBytes;
  34. // Init sbox
  35. this._S = [];
  36. const S = this._S;
  37. for (let i = 0; i < 256; i += 1) {
  38. S[i] = i;
  39. }
  40. // Key setup
  41. for (let i = 0, j = 0; i < 256; i += 1) {
  42. const keyByteIndex = i % keySigBytes;
  43. const keyByte = (keyWords[keyByteIndex >>> 2] >>> (24 - (keyByteIndex % 4) * 8)) & 0xff;
  44. j = (j + S[i] + keyByte) % 256;
  45. // Swap
  46. const t = S[i];
  47. S[i] = S[j];
  48. S[j] = t;
  49. }
  50. // Counters
  51. this._j = 0;
  52. this._i = this._j;
  53. }
  54. _doProcessBlock(M, offset) {
  55. const _M = M;
  56. _M[offset] ^= generateKeystreamWord.call(this);
  57. }
  58. }
  59. RC4Algo.keySize = 256 / 32;
  60. RC4Algo.ivSize = 0;
  61. /**
  62. * Shortcut functions to the cipher's object interface.
  63. *
  64. * @example
  65. *
  66. * var ciphertext = CryptoJS.RC4.encrypt(message, key, cfg);
  67. * var plaintext = CryptoJS.RC4.decrypt(ciphertext, key, cfg);
  68. */
  69. export const RC4 = StreamCipher._createHelper(RC4Algo);
  70. /**
  71. * Modified RC4 stream cipher algorithm.
  72. */
  73. export class RC4DropAlgo extends RC4Algo {
  74. constructor(...args) {
  75. super(...args);
  76. /**
  77. * Configuration options.
  78. *
  79. * @property {number} drop The number of keystream words to drop. Default 192
  80. */
  81. Object.assign(this.cfg, { drop: 192 });
  82. }
  83. _doReset() {
  84. super._doReset.call(this);
  85. // Drop
  86. for (let i = this.cfg.drop; i > 0; i -= 1) {
  87. generateKeystreamWord.call(this);
  88. }
  89. }
  90. }
  91. /**
  92. * Shortcut functions to the cipher's object interface.
  93. *
  94. * @example
  95. *
  96. * var ciphertext = CryptoJS.RC4Drop.encrypt(message, key, cfg);
  97. * var plaintext = CryptoJS.RC4Drop.decrypt(ciphertext, key, cfg);
  98. */
  99. export const RC4Drop = StreamCipher._createHelper(RC4DropAlgo);