UrlAndHash.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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.Utilities;
  6. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls
  7. {
  8. /// <summary>RFC 6066 5.</summary>
  9. public sealed class UrlAndHash
  10. {
  11. private readonly string m_url;
  12. private readonly byte[] m_sha1Hash;
  13. public UrlAndHash(string url, byte[] sha1Hash)
  14. {
  15. if (TlsUtilities.IsNullOrEmpty(url) || url.Length >= (1 << 16))
  16. throw new ArgumentException("must have length from 1 to (2^16 - 1)", "url");
  17. if (sha1Hash != null && sha1Hash.Length != 20)
  18. throw new ArgumentException("must have length == 20, if present", "sha1Hash");
  19. this.m_url = url;
  20. this.m_sha1Hash = sha1Hash;
  21. }
  22. public string Url
  23. {
  24. get { return m_url; }
  25. }
  26. public byte[] Sha1Hash
  27. {
  28. get { return m_sha1Hash; }
  29. }
  30. /// <summary>Encode this <see cref="UrlAndHash"/> to a <see cref="Stream"/>.</summary>
  31. /// <param name="output">the <see cref="Stream"/> to encode to.</param>
  32. /// <exception cref="IOException"/>
  33. public void Encode(Stream output)
  34. {
  35. byte[] urlEncoding = Strings.ToByteArray(m_url);
  36. TlsUtilities.WriteOpaque16(urlEncoding, output);
  37. if (m_sha1Hash == null)
  38. {
  39. TlsUtilities.WriteUint8(0, output);
  40. }
  41. else
  42. {
  43. TlsUtilities.WriteUint8(1, output);
  44. output.Write(m_sha1Hash, 0, m_sha1Hash.Length);
  45. }
  46. }
  47. /// <summary>Parse a <see cref="UrlAndHash"/> from a <see cref="Stream"/>.</summary>
  48. /// <param name="context">the <see cref="TlsContext"/> of the current connection.</param>
  49. /// <param name="input">the <see cref="Stream"/> to parse from.</param>
  50. /// <returns>a <see cref="UrlAndHash"/> object.</returns>
  51. /// <exception cref="IOException"/>
  52. public static UrlAndHash Parse(TlsContext context, Stream input)
  53. {
  54. byte[] urlEncoding = TlsUtilities.ReadOpaque16(input, 1);
  55. string url = Strings.FromByteArray(urlEncoding);
  56. byte[] sha1Hash = null;
  57. short padding = TlsUtilities.ReadUint8(input);
  58. switch (padding)
  59. {
  60. case 0:
  61. if (TlsUtilities.IsTlsV12(context))
  62. throw new TlsFatalAlert(AlertDescription.illegal_parameter);
  63. break;
  64. case 1:
  65. sha1Hash = TlsUtilities.ReadFully(20, input);
  66. break;
  67. default:
  68. throw new TlsFatalAlert(AlertDescription.illegal_parameter);
  69. }
  70. return new UrlAndHash(url, sha1Hash);
  71. }
  72. }
  73. }
  74. #pragma warning restore
  75. #endif