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.

StreamCrypto.cs 6.1 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. using NLog;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Runtime.CompilerServices;
  5. using System.Text;
  6. namespace Shadowsocks.Crypto.Stream
  7. {
  8. public abstract class StreamCrypto : CryptoBase
  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 StreamCrypto(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. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  45. public static void LegacyDeriveKey(byte[] password, byte[] key, int keylen)
  46. {
  47. byte[] result = new byte[password.Length + MD5Length];
  48. int i = 0;
  49. byte[] md5sum = Array.Empty<byte>();
  50. while (i < keylen)
  51. {
  52. if (i == 0)
  53. {
  54. md5sum = CryptoUtils.MD5(password);
  55. }
  56. else
  57. {
  58. Array.Copy(md5sum, 0, result, 0, MD5Length);
  59. Array.Copy(password, 0, result, MD5Length, password.Length);
  60. md5sum = CryptoUtils.MD5(result);
  61. }
  62. Array.Copy(md5sum, 0, key, i, Math.Min(MD5Length, keylen - i));
  63. i += MD5Length;
  64. }
  65. }
  66. protected virtual void InitCipher(byte[] iv, bool isEncrypt)
  67. {
  68. if (ivLen == 0)
  69. {
  70. return;
  71. }
  72. this.iv = new byte[ivLen];
  73. Array.Copy(iv, this.iv, ivLen);
  74. }
  75. protected abstract int CipherEncrypt(ReadOnlySpan<byte> plain, Span<byte> cipher);
  76. protected abstract int CipherDecrypt(Span<byte> plain, ReadOnlySpan<byte> cipher);
  77. #region TCP
  78. [MethodImpl(MethodImplOptions.Synchronized)]
  79. public override int Encrypt(ReadOnlySpan<byte> plain, Span<byte> cipher)
  80. {
  81. int cipherOffset = 0;
  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. ivBytes.CopyTo(cipher);
  89. cipherOffset = ivLen;
  90. cipher = cipher.Slice(cipherOffset);
  91. ivReady = true;
  92. }
  93. int clen = CipherEncrypt(plain, cipher);
  94. logger.DumpBase64($"plain {instanceId}", plain);
  95. logger.DumpBase64($"cipher {instanceId}", cipher.Slice(0, clen));
  96. logger.Dump($"iv {instanceId}", iv, ivLen);
  97. return clen + cipherOffset;
  98. }
  99. private int recieveCtr = 0;
  100. [MethodImpl(MethodImplOptions.Synchronized)]
  101. public override int Decrypt(Span<byte> plain, ReadOnlySpan<byte> cipher)
  102. {
  103. logger.Trace($"{instanceId} decrypt TCP, read iv: {!ivReady}");
  104. int cipherOffset = 0;
  105. // is first packet, need read iv
  106. if (!ivReady)
  107. {
  108. // push to buffer in case of not enough data
  109. cipher.CopyTo(sharedBuffer.AsSpan(recieveCtr));
  110. recieveCtr += cipher.Length;
  111. // not enough data for read iv, return 0 byte data
  112. if (recieveCtr <= ivLen)
  113. {
  114. return 0;
  115. }
  116. // start decryption
  117. ivReady = true;
  118. if (ivLen > 0)
  119. {
  120. // read iv
  121. byte[] iv = sharedBuffer.AsSpan(0, ivLen).ToArray();
  122. InitCipher(iv, false);
  123. }
  124. else
  125. {
  126. InitCipher(Array.Empty<byte>(), false);
  127. }
  128. cipherOffset += ivLen;
  129. }
  130. // read all data from buffer
  131. int len = CipherDecrypt(plain, cipher.Slice(cipherOffset));
  132. logger.DumpBase64($"cipher {instanceId}", cipher.Slice(cipherOffset));
  133. logger.DumpBase64($"plain {instanceId}", plain.Slice(0, len));
  134. logger.Dump($"iv {instanceId}", iv, ivLen);
  135. return len;
  136. }
  137. #endregion
  138. #region UDP
  139. [MethodImpl(MethodImplOptions.Synchronized)]
  140. public override int EncryptUDP(ReadOnlySpan<byte> plain, Span<byte> cipher)
  141. {
  142. byte[] iv = RNG.GetBytes(ivLen);
  143. iv.CopyTo(cipher);
  144. InitCipher(iv, true);
  145. return ivLen + CipherEncrypt(plain, cipher.Slice(ivLen));
  146. }
  147. [MethodImpl(MethodImplOptions.Synchronized)]
  148. public override int DecryptUDP(Span<byte> plain, ReadOnlySpan<byte> cipher)
  149. {
  150. InitCipher(cipher.Slice(0, ivLen).ToArray(), false);
  151. return CipherDecrypt(plain, cipher.Slice(ivLen));
  152. }
  153. #endregion
  154. }
  155. }