UrlAndHash.cs 3.0 KB

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