libs/rc4.js

  1. /**
  2. * @license
  3. * FPDF is released under a permissive license: there is no usage restriction.
  4. * You may embed it freely in your application (commercial or not), with or
  5. * without modifications.
  6. *
  7. * Reference: http://www.fpdf.org/en/script/script37.php
  8. */
  9. function repeat(str, num) {
  10. return new Array(num + 1).join(str);
  11. }
  12. /**
  13. * Converts a byte string to a hex string
  14. *
  15. * @name rc4
  16. * @function
  17. * @param {string} key Byte string of encryption key
  18. * @param {string} data Byte string of data to be encrypted
  19. * @returns {string} Encrypted string
  20. */
  21. function rc4(key, data) {
  22. var lastKey, lastState;
  23. if (key !== lastKey) {
  24. var k = repeat(key, ((256 / key.length) >> 0) + 1);
  25. var state = [];
  26. for (var i = 0; i < 256; i++) {
  27. state[i] = i;
  28. }
  29. var j = 0;
  30. for (var i = 0; i < 256; i++) {
  31. var t = state[i];
  32. j = (j + t + k.charCodeAt(i)) % 256;
  33. state[i] = state[j];
  34. state[j] = t;
  35. }
  36. lastKey = key;
  37. lastState = state;
  38. } else {
  39. state = lastState;
  40. }
  41. var length = data.length;
  42. var a = 0;
  43. var b = 0;
  44. var out = "";
  45. for (var i = 0; i < length; i++) {
  46. a = (a + 1) % 256;
  47. t = state[a];
  48. b = (b + t) % 256;
  49. state[a] = state[b];
  50. state[b] = t;
  51. k = state[(state[a] + state[b]) % 256];
  52. out += String.fromCharCode(data.charCodeAt(i) ^ k);
  53. }
  54. return out;
  55. }
  56. export { rc4 };