You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

RC4.cs 1.7 kB

12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. namespace shadowsocks_csharp
  5. {
  6. public class RC4
  7. {
  8. class Context
  9. {
  10. public int index1 = 0;
  11. public int index2 = 0;
  12. }
  13. private Context enc_ctx = new Context();
  14. private Context dec_ctx = new Context();
  15. public void Encrypt(byte[] table, byte[] data, int length)
  16. {
  17. EncryptOutput(enc_ctx, table, data, length);
  18. }
  19. public void Decrypt(byte[] table, byte[] data, int length)
  20. {
  21. EncryptOutput(dec_ctx, table, data, length);
  22. }
  23. public byte[] EncryptInitalize(byte[] key)
  24. {
  25. byte[] s = new byte[256];
  26. for (int i = 0; i < 256; i++)
  27. {
  28. s[i] = (byte)i;
  29. }
  30. for (int i = 0, j = 0; i < 256; i++)
  31. {
  32. j = (j + key[i % key.Length] + s[i]) & 255;
  33. Swap(s, i, j);
  34. }
  35. return s;
  36. }
  37. private void EncryptOutput(Context ctx, byte[] s, byte[] data, int length)
  38. {
  39. for (int n = 0; n < length; n++)
  40. {
  41. byte b = data[n];
  42. ctx.index1 = (ctx.index1 + 1) & 255;
  43. ctx.index2 = (ctx.index2 + s[ctx.index1]) & 255;
  44. Swap(s, ctx.index1, ctx.index2);
  45. data[n] = (byte)(b ^ s[(s[ctx.index1] + s[ctx.index2]) & 255]);
  46. }
  47. }
  48. private static void Swap(byte[] s, int i, int j)
  49. {
  50. byte c = s[i];
  51. s[i] = s[j];
  52. s[j] = c;
  53. }
  54. }
  55. }

No Description