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.

Encryptor.cs 3.0 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
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Security.Cryptography;
  6. namespace shadowsocks_csharp
  7. {
  8. class Encryptor
  9. {
  10. public byte[] encryptTable = new byte[256];
  11. public byte[] decryptTable = new byte[256];
  12. private Int64 compare(byte x, byte y, UInt64 a, int i) {
  13. return (Int64)(a % (UInt64)(x + i)) - (Int64)(a % (UInt64)(y + i));
  14. }
  15. private byte[] mergeSort(byte[] array, UInt64 a, int j)
  16. {
  17. if (array.Length == 1)
  18. return array;
  19. int middle = array.Length / 2;
  20. byte[] left = new byte[middle];
  21. for (int i = 0; i < middle; i++)
  22. {
  23. left[i] = array[i];
  24. }
  25. byte[] right = new byte[array.Length - middle];
  26. for (int i = 0; i < array.Length - middle; i++)
  27. {
  28. right[i] = array[i + middle];
  29. }
  30. left = mergeSort(left, a, j);
  31. right = mergeSort(right, a, j);
  32. int leftptr = 0;
  33. int rightptr = 0;
  34. byte[] sorted = new byte[array.Length];
  35. for (int k = 0; k < array.Length; k++)
  36. {
  37. if (rightptr == right.Length || ((leftptr < left.Length) && (compare(left[leftptr], right[rightptr], a, j) <= 0)))
  38. {
  39. sorted[k] = left[leftptr];
  40. leftptr++;
  41. }
  42. else if (leftptr == left.Length || ((rightptr < right.Length) && (compare(right[rightptr], left[leftptr], a, j)) <= 0))
  43. {
  44. sorted[k] = right[rightptr];
  45. rightptr++;
  46. }
  47. }
  48. return sorted;
  49. }
  50. public Encryptor(string password)
  51. {
  52. MD5 md5 = System.Security.Cryptography.MD5.Create();
  53. byte[] inputBytes = System.Text.Encoding.UTF8.GetBytes(password);
  54. byte[] hash = md5.ComputeHash(inputBytes);
  55. // TODO endian
  56. var a = BitConverter.ToUInt64(hash, 0);
  57. for (int i = 0; i < 256; i++)
  58. {
  59. encryptTable[i] = (byte)i;
  60. }
  61. for (int i = 1; i < 1024; i++)
  62. {
  63. encryptTable = mergeSort(encryptTable, a, i);
  64. }
  65. for (int i = 0; i < 256; i++)
  66. {
  67. decryptTable[encryptTable[i]] = (byte)i;
  68. }
  69. }
  70. public void Encrypt(byte[] buf, int length)
  71. {
  72. for (int i = 0; i < length; i++)
  73. {
  74. buf[i] = encryptTable[buf[i]];
  75. }
  76. }
  77. public void Decrypt(byte[] buf, int length)
  78. {
  79. for (int i = 0; i < length; i++)
  80. {
  81. buf[i] = decryptTable[buf[i]];
  82. }
  83. }
  84. }
  85. }

No Description

Contributors (1)