Chacha20Poly1305.cs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.IO;
  5. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines;
  6. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators;
  7. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Macs;
  8. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
  9. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
  10. using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
  11. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  12. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Tls
  13. {
  14. /**
  15. * draft-ietf-tls-chacha20-poly1305-04
  16. */
  17. public class Chacha20Poly1305
  18. : TlsCipher
  19. {
  20. private static readonly byte[] Zeroes = new byte[15];
  21. protected readonly TlsContext context;
  22. protected readonly ChaCha7539Engine encryptCipher, decryptCipher;
  23. protected readonly byte[] encryptIV, decryptIV;
  24. /// <exception cref="IOException"></exception>
  25. public Chacha20Poly1305(TlsContext context)
  26. {
  27. if (!TlsUtilities.IsTlsV12(context))
  28. throw new TlsFatalAlert(AlertDescription.internal_error);
  29. this.context = context;
  30. int cipherKeySize = 32;
  31. // TODO SecurityParameters.fixed_iv_length
  32. int fixed_iv_length = 12;
  33. // TODO SecurityParameters.record_iv_length = 0
  34. int key_block_size = (2 * cipherKeySize) + (2 * fixed_iv_length);
  35. byte[] key_block = TlsUtilities.CalculateKeyBlock(context, key_block_size);
  36. int offset = 0;
  37. KeyParameter client_write_key = new KeyParameter(key_block, offset, cipherKeySize);
  38. offset += cipherKeySize;
  39. KeyParameter server_write_key = new KeyParameter(key_block, offset, cipherKeySize);
  40. offset += cipherKeySize;
  41. byte[] client_write_IV = Arrays.CopyOfRange(key_block, offset, offset + fixed_iv_length);
  42. offset += fixed_iv_length;
  43. byte[] server_write_IV = Arrays.CopyOfRange(key_block, offset, offset + fixed_iv_length);
  44. offset += fixed_iv_length;
  45. if (offset != key_block_size)
  46. throw new TlsFatalAlert(AlertDescription.internal_error);
  47. this.encryptCipher = new ChaCha7539Engine();
  48. this.decryptCipher = new ChaCha7539Engine();
  49. KeyParameter encryptKey, decryptKey;
  50. if (context.IsServer)
  51. {
  52. encryptKey = server_write_key;
  53. decryptKey = client_write_key;
  54. this.encryptIV = server_write_IV;
  55. this.decryptIV = client_write_IV;
  56. }
  57. else
  58. {
  59. encryptKey = client_write_key;
  60. decryptKey = server_write_key;
  61. this.encryptIV = client_write_IV;
  62. this.decryptIV = server_write_IV;
  63. }
  64. this.encryptCipher.Init(true, new ParametersWithIV(encryptKey, encryptIV));
  65. this.decryptCipher.Init(false, new ParametersWithIV(decryptKey, decryptIV));
  66. }
  67. public virtual int GetPlaintextLimit(int ciphertextLimit)
  68. {
  69. return ciphertextLimit - 16;
  70. }
  71. /// <exception cref="IOException"></exception>
  72. public virtual byte[] EncodePlaintext(long seqNo, byte type, byte[] plaintext, int offset, int len)
  73. {
  74. KeyParameter macKey = InitRecord(encryptCipher, true, seqNo, encryptIV);
  75. byte[] output = new byte[len + 16];
  76. encryptCipher.ProcessBytes(plaintext, offset, len, output, 0);
  77. byte[] additionalData = GetAdditionalData(seqNo, type, len);
  78. byte[] mac = CalculateRecordMac(macKey, additionalData, output, 0, len);
  79. Array.Copy(mac, 0, output, len, mac.Length);
  80. return output;
  81. }
  82. /// <exception cref="IOException"></exception>
  83. public virtual byte[] DecodeCiphertext(long seqNo, byte type, byte[] ciphertext, int offset, int len)
  84. {
  85. if (GetPlaintextLimit(len) < 0)
  86. throw new TlsFatalAlert(AlertDescription.decode_error);
  87. KeyParameter macKey = InitRecord(decryptCipher, false, seqNo, decryptIV);
  88. int plaintextLength = len - 16;
  89. byte[] additionalData = GetAdditionalData(seqNo, type, plaintextLength);
  90. byte[] calculatedMac = CalculateRecordMac(macKey, additionalData, ciphertext, offset, plaintextLength);
  91. byte[] receivedMac = Arrays.CopyOfRange(ciphertext, offset + plaintextLength, offset + len);
  92. if (!Arrays.ConstantTimeAreEqual(calculatedMac, receivedMac))
  93. throw new TlsFatalAlert(AlertDescription.bad_record_mac);
  94. byte[] output = new byte[plaintextLength];
  95. decryptCipher.ProcessBytes(ciphertext, offset, plaintextLength, output, 0);
  96. return output;
  97. }
  98. protected virtual KeyParameter InitRecord(IStreamCipher cipher, bool forEncryption, long seqNo, byte[] iv)
  99. {
  100. byte[] nonce = CalculateNonce(seqNo, iv);
  101. cipher.Init(forEncryption, new ParametersWithIV(null, nonce));
  102. return GenerateRecordMacKey(cipher);
  103. }
  104. protected virtual byte[] CalculateNonce(long seqNo, byte[] iv)
  105. {
  106. byte[] nonce = new byte[12];
  107. TlsUtilities.WriteUint64(seqNo, nonce, 4);
  108. for (int i = 0; i < 12; ++i)
  109. {
  110. nonce[i] ^= iv[i];
  111. }
  112. return nonce;
  113. }
  114. protected virtual KeyParameter GenerateRecordMacKey(IStreamCipher cipher)
  115. {
  116. byte[] firstBlock = new byte[64];
  117. cipher.ProcessBytes(firstBlock, 0, firstBlock.Length, firstBlock, 0);
  118. KeyParameter macKey = new KeyParameter(firstBlock, 0, 32);
  119. Arrays.Fill(firstBlock, (byte)0);
  120. return macKey;
  121. }
  122. protected virtual byte[] CalculateRecordMac(KeyParameter macKey, byte[] additionalData, byte[] buf, int off, int len)
  123. {
  124. IMac mac = new Poly1305();
  125. mac.Init(macKey);
  126. UpdateRecordMacText(mac, additionalData, 0, additionalData.Length);
  127. UpdateRecordMacText(mac, buf, off, len);
  128. UpdateRecordMacLength(mac, additionalData.Length);
  129. UpdateRecordMacLength(mac, len);
  130. return MacUtilities.DoFinal(mac);
  131. }
  132. protected virtual void UpdateRecordMacLength(IMac mac, int len)
  133. {
  134. byte[] longLen = Pack.UInt64_To_LE((ulong)len);
  135. mac.BlockUpdate(longLen, 0, longLen.Length);
  136. }
  137. protected virtual void UpdateRecordMacText(IMac mac, byte[] buf, int off, int len)
  138. {
  139. mac.BlockUpdate(buf, off, len);
  140. int partial = len % 16;
  141. if (partial != 0)
  142. {
  143. mac.BlockUpdate(Zeroes, 0, 16 - partial);
  144. }
  145. }
  146. /// <exception cref="IOException"></exception>
  147. protected virtual byte[] GetAdditionalData(long seqNo, byte type, int len)
  148. {
  149. /*
  150. * additional_data = seq_num + TLSCompressed.type + TLSCompressed.version +
  151. * TLSCompressed.length
  152. */
  153. byte[] additional_data = new byte[13];
  154. TlsUtilities.WriteUint64(seqNo, additional_data, 0);
  155. TlsUtilities.WriteUint8(type, additional_data, 8);
  156. TlsUtilities.WriteVersion(context.ServerVersion, additional_data, 9);
  157. TlsUtilities.WriteUint16(len, additional_data, 11);
  158. return additional_data;
  159. }
  160. }
  161. }
  162. #pragma warning restore
  163. #endif