Chacha20Poly1305.cs 7.3 KB

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