HandshakeMessageOutput.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.IO;
  5. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  6. namespace Best.HTTP.SecureProtocol.Org.BouncyCastle.Tls
  7. {
  8. internal sealed class HandshakeMessageOutput
  9. : MemoryStream
  10. {
  11. internal static int GetLength(int bodyLength)
  12. {
  13. return 4 + bodyLength;
  14. }
  15. /// <exception cref="IOException"/>
  16. internal static void Send(TlsProtocol protocol, short handshakeType, byte[] body)
  17. {
  18. HandshakeMessageOutput message = new HandshakeMessageOutput(handshakeType, body.Length);
  19. message.Write(body, 0, body.Length);
  20. message.Send(protocol);
  21. }
  22. /// <exception cref="IOException"/>
  23. internal HandshakeMessageOutput(short handshakeType)
  24. : this(handshakeType, 60)
  25. {
  26. }
  27. /// <exception cref="IOException"/>
  28. internal HandshakeMessageOutput(short handshakeType, int bodyLength)
  29. : base(GetLength(bodyLength))
  30. {
  31. TlsUtilities.CheckUint8(handshakeType);
  32. TlsUtilities.WriteUint8(handshakeType, this);
  33. // Reserve space for length
  34. Seek(3L, SeekOrigin.Current);
  35. }
  36. /// <exception cref="IOException"/>
  37. internal void Send(TlsProtocol protocol)
  38. {
  39. // Patch actual length back in
  40. int bodyLength = Convert.ToInt32(Length) - 4;
  41. TlsUtilities.CheckUint24(bodyLength);
  42. Seek(1L, SeekOrigin.Begin);
  43. TlsUtilities.WriteUint24(bodyLength, this);
  44. byte[] buf = GetBuffer();
  45. int count = Convert.ToInt32(Length);
  46. protocol.WriteHandshakeMessage(buf, 0, count);
  47. Dispose();
  48. }
  49. internal void PrepareClientHello(TlsHandshakeHash handshakeHash, int bindersSize)
  50. {
  51. // Patch actual length back in
  52. int bodyLength = Convert.ToInt32(Length) - 4 + bindersSize;
  53. TlsUtilities.CheckUint24(bodyLength);
  54. Seek(1L, SeekOrigin.Begin);
  55. TlsUtilities.WriteUint24(bodyLength, this);
  56. byte[] buf = GetBuffer();
  57. int count = Convert.ToInt32(Length);
  58. handshakeHash.Update(buf, 0, count);
  59. Seek(0L, SeekOrigin.End);
  60. }
  61. internal void SendClientHello(TlsClientProtocol clientProtocol, TlsHandshakeHash handshakeHash, int bindersSize)
  62. {
  63. byte[] buf = GetBuffer();
  64. int count = Convert.ToInt32(Length);
  65. if (bindersSize > 0)
  66. {
  67. handshakeHash.Update(buf, count - bindersSize, bindersSize);
  68. }
  69. clientProtocol.WriteHandshakeMessage(buf, 0, count);
  70. Dispose();
  71. }
  72. }
  73. }
  74. #pragma warning restore
  75. #endif