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.

StreamEncryptor.cs 6.9 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. using NLog;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Runtime.CompilerServices;
  5. using System.Text;
  6. namespace Shadowsocks.Encryption.Stream
  7. {
  8. public abstract class StreamEncryptor : EncryptorBase
  9. {
  10. private static readonly Logger logger = LogManager.GetCurrentClassLogger();
  11. // shared by TCP decrypt UDP encrypt and decrypt
  12. protected static byte[] sharedBuffer = new byte[65536];
  13. // Is first packet
  14. protected bool ivReady;
  15. protected CipherFamily cipherFamily;
  16. protected CipherInfo CipherInfo;
  17. // long-time master key
  18. protected static byte[] key = Array.Empty<byte>();
  19. protected byte[] iv = Array.Empty<byte>();
  20. protected int keyLen;
  21. protected int ivLen;
  22. public StreamEncryptor(string method, string password)
  23. : base(method, password)
  24. {
  25. CipherInfo = getCiphers()[method.ToLower()];
  26. cipherFamily = CipherInfo.Type;
  27. StreamCipherParameter parameter = (StreamCipherParameter)CipherInfo.CipherParameter;
  28. keyLen = parameter.KeySize;
  29. ivLen = parameter.IvSize;
  30. InitKey(password);
  31. logger.Dump($"key {instanceId}", key, keyLen);
  32. }
  33. protected abstract Dictionary<string, CipherInfo> getCiphers();
  34. private void InitKey(string password)
  35. {
  36. byte[] passbuf = Encoding.UTF8.GetBytes(password);
  37. key ??= new byte[keyLen];
  38. if (key.Length != keyLen)
  39. {
  40. Array.Resize(ref key, keyLen);
  41. }
  42. LegacyDeriveKey(passbuf, key, keyLen);
  43. }
  44. public static void LegacyDeriveKey(byte[] password, byte[] key, int keylen)
  45. {
  46. byte[] result = new byte[password.Length + MD5Length];
  47. int i = 0;
  48. byte[] md5sum = Array.Empty<byte>();
  49. while (i < keylen)
  50. {
  51. if (i == 0)
  52. {
  53. md5sum = CryptoUtils.MD5(password);
  54. }
  55. else
  56. {
  57. Array.Copy(md5sum, 0, result, 0, MD5Length);
  58. Array.Copy(password, 0, result, MD5Length, password.Length);
  59. md5sum = CryptoUtils.MD5(result);
  60. }
  61. Array.Copy(md5sum, 0, key, i, Math.Min(MD5Length, keylen - i));
  62. i += MD5Length;
  63. }
  64. }
  65. protected virtual void initCipher(byte[] iv, bool isEncrypt)
  66. {
  67. if (ivLen == 0)
  68. {
  69. return;
  70. }
  71. this.iv = new byte[ivLen];
  72. Array.Copy(iv, this.iv, ivLen);
  73. }
  74. protected abstract int CipherEncrypt(Span<byte> plain, Span<byte> cipher);
  75. protected abstract int CipherDecrypt(Span<byte> plain, Span<byte> cipher);
  76. #region TCP
  77. [MethodImpl(MethodImplOptions.Synchronized)]
  78. public override void Encrypt(byte[] buf, int length, byte[] outbuf, out int outlength)
  79. {
  80. int cipherOffset = 0;
  81. Span<byte> tmp = buf.AsSpan(0, length);
  82. logger.Trace($"{instanceId} encrypt TCP, generate iv: {!ivReady}");
  83. if (!ivReady)
  84. {
  85. // Generate IV
  86. byte[] ivBytes = RNG.GetBytes(ivLen);
  87. initCipher(ivBytes, true);
  88. Array.Copy(ivBytes, 0, outbuf, 0, ivLen);
  89. cipherOffset = ivLen;
  90. ivReady = true;
  91. }
  92. int size = tmp.Length;
  93. byte[] cipher = new byte[size];
  94. CipherEncrypt(tmp, cipher);
  95. logger.DumpBase64($"plain {instanceId}", tmp.ToArray(), size);
  96. logger.DumpBase64($"cipher {instanceId}", cipher, cipher.Length);
  97. logger.Dump($"iv {instanceId}", iv, ivLen);
  98. Buffer.BlockCopy(cipher, 0, outbuf, cipherOffset, size);
  99. outlength = size + cipherOffset;
  100. }
  101. private int recieveCtr = 0;
  102. [MethodImpl(MethodImplOptions.Synchronized)]
  103. public override void Decrypt(byte[] buf, int length, byte[] outbuf, out int outlength)
  104. {
  105. Span<byte> tmp = buf.AsSpan(0, length);
  106. logger.Trace($"{instanceId} decrypt TCP, read iv: {!ivReady}");
  107. // is first packet, need read iv
  108. if (!ivReady)
  109. {
  110. // push to buffer in case of not enough data
  111. tmp.CopyTo(sharedBuffer.AsSpan(recieveCtr));
  112. recieveCtr += tmp.Length;
  113. // not enough data for read iv, return 0 byte data
  114. if (recieveCtr <= ivLen)
  115. {
  116. outlength = 0;
  117. return;
  118. }
  119. // start decryption
  120. ivReady = true;
  121. if (ivLen > 0)
  122. {
  123. // read iv
  124. byte[] iv = sharedBuffer.AsSpan(0, ivLen).ToArray();
  125. initCipher(iv, false);
  126. }
  127. else
  128. {
  129. initCipher(Array.Empty<byte>(), false);
  130. }
  131. tmp = sharedBuffer.AsSpan(ivLen, recieveCtr - ivLen);
  132. }
  133. // read all data from buffer
  134. CipherDecrypt(outbuf, tmp);
  135. logger.DumpBase64($"cipher {instanceId}", tmp.ToArray(), tmp.Length);
  136. logger.DumpBase64($"plain {instanceId}", outbuf, tmp.Length);
  137. logger.Dump($"iv {instanceId}", iv, ivLen);
  138. outlength = tmp.Length;
  139. }
  140. #endregion
  141. #region UDP
  142. [MethodImpl(MethodImplOptions.Synchronized)]
  143. public override void EncryptUDP(byte[] buf, int length, byte[] outbuf, out int outlength)
  144. {
  145. // Generate IV
  146. RNG.GetBytes(outbuf, ivLen);
  147. initCipher(outbuf, true);
  148. lock (sharedBuffer)
  149. {
  150. CipherEncrypt(buf, sharedBuffer);
  151. outlength = length + ivLen;
  152. Buffer.BlockCopy(sharedBuffer, 0, outbuf, ivLen, length);
  153. }
  154. }
  155. [MethodImpl(MethodImplOptions.Synchronized)]
  156. public override void DecryptUDP(byte[] buf, int length, byte[] outbuf, out int outlength)
  157. {
  158. // Get IV from first pos
  159. initCipher(buf, false);
  160. outlength = length - ivLen;
  161. lock (sharedBuffer)
  162. {
  163. // C# could be multi-threaded
  164. Buffer.BlockCopy(buf, ivLen, sharedBuffer, 0, length - ivLen);
  165. CipherDecrypt(outbuf, sharedBuffer);
  166. }
  167. }
  168. #endregion
  169. }
  170. }