marc4.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. /*!
  2. * Crypto-JS v1.1.0
  3. * http://code.google.com/p/crypto-js/
  4. * Copyright (c) 2009, Jeff Mott. All rights reserved.
  5. * http://code.google.com/p/crypto-js/wiki/License
  6. */
  7. (function(){
  8. // Shortcut
  9. var util = Crypto.util;
  10. var MARC4 = Crypto.MARC4 = {
  11. /**
  12. * Public API
  13. */
  14. encrypt: function (message, password) {
  15. var
  16. // Convert to bytes
  17. m = util.stringToBytes(message),
  18. // Generate random IV
  19. iv = util.randomBytes(16),
  20. // Generate key
  21. k = Crypto.PBKDF2(password, util.bytesToString(iv), 32, { asBytes: true });
  22. // Encrypt
  23. MARC4._marc4(m, k, 1536);
  24. // Return ciphertext
  25. return util.bytesToBase64(iv.concat(m));
  26. },
  27. decrypt: function (ciphertext, password) {
  28. var
  29. // Convert to bytes
  30. c = util.base64ToBytes(ciphertext),
  31. // Separate IV and message
  32. iv = c.splice(0, 16),
  33. // Generate key
  34. k = Crypto.PBKDF2(password, util.bytesToString(iv), 32, { asBytes: true });
  35. // Decrypt
  36. MARC4._marc4(c, k, 1536);
  37. // Return plaintext
  38. return util.bytesToString(c);
  39. },
  40. /**
  41. * Internal methods
  42. */
  43. // The core
  44. _marc4: function (m, k, drop) {
  45. // State variables
  46. var i, j, s, temp;
  47. // Key setup
  48. for (i = 0, s = []; i < 256; i++) s[i] = i;
  49. for (i = 0, j = 0; i < 256; i++) {
  50. j = (j + s[i] + k[i % k.length]) % 256;
  51. // Swap
  52. temp = s[i];
  53. s[i] = s[j];
  54. s[j] = temp;
  55. }
  56. // Clear counters
  57. i = j = 0;
  58. // Encryption
  59. for (var k = 0 - drop; k < m.length; k++) {
  60. i = (i + 1) % 256;
  61. j = (j + s[i]) % 256;
  62. // Swap
  63. temp = s[i];
  64. s[i] = s[j];
  65. s[j] = temp;
  66. // Stop here if we're still dropping keystream
  67. if (k < 0) continue;
  68. // Encrypt
  69. m[k] ^= s[(s[i] + s[j]) % 256];
  70. }
  71. }
  72. };
  73. })();