ServerName.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. using System;
  3. using System.IO;
  4. using Org.BouncyCastle.Utilities;
  5. namespace Org.BouncyCastle.Crypto.Tls
  6. {
  7. public class ServerName
  8. {
  9. protected readonly byte mNameType;
  10. protected readonly object mName;
  11. public ServerName(byte nameType, object name)
  12. {
  13. if (!IsCorrectType(nameType, name))
  14. throw new ArgumentException("not an instance of the correct type", "name");
  15. this.mNameType = nameType;
  16. this.mName = name;
  17. }
  18. public virtual byte NameType
  19. {
  20. get { return mNameType; }
  21. }
  22. public virtual object Name
  23. {
  24. get { return mName; }
  25. }
  26. public virtual string GetHostName()
  27. {
  28. if (!IsCorrectType(Tls.NameType.host_name, mName))
  29. throw new InvalidOperationException("'name' is not a HostName string");
  30. return (string)mName;
  31. }
  32. /**
  33. * Encode this {@link ServerName} to a {@link Stream}.
  34. *
  35. * @param output
  36. * the {@link Stream} to encode to.
  37. * @throws IOException
  38. */
  39. public virtual void Encode(Stream output)
  40. {
  41. TlsUtilities.WriteUint8(mNameType, output);
  42. switch (mNameType)
  43. {
  44. case Tls.NameType.host_name:
  45. byte[] asciiEncoding = Strings.ToAsciiByteArray((string)mName);
  46. if (asciiEncoding.Length < 1)
  47. throw new TlsFatalAlert(AlertDescription.internal_error);
  48. TlsUtilities.WriteOpaque16(asciiEncoding, output);
  49. break;
  50. default:
  51. throw new TlsFatalAlert(AlertDescription.internal_error);
  52. }
  53. }
  54. /**
  55. * Parse a {@link ServerName} from a {@link Stream}.
  56. *
  57. * @param input
  58. * the {@link Stream} to parse from.
  59. * @return a {@link ServerName} object.
  60. * @throws IOException
  61. */
  62. public static ServerName Parse(Stream input)
  63. {
  64. byte name_type = TlsUtilities.ReadUint8(input);
  65. object name;
  66. switch (name_type)
  67. {
  68. case Tls.NameType.host_name:
  69. {
  70. byte[] asciiEncoding = TlsUtilities.ReadOpaque16(input);
  71. if (asciiEncoding.Length < 1)
  72. throw new TlsFatalAlert(AlertDescription.decode_error);
  73. name = Strings.FromAsciiByteArray(asciiEncoding);
  74. break;
  75. }
  76. default:
  77. throw new TlsFatalAlert(AlertDescription.decode_error);
  78. }
  79. return new ServerName(name_type, name);
  80. }
  81. protected static bool IsCorrectType(byte nameType, object name)
  82. {
  83. switch (nameType)
  84. {
  85. case Tls.NameType.host_name:
  86. return name is string;
  87. default:
  88. throw new ArgumentException("unsupported value", "name");
  89. }
  90. }
  91. }
  92. }
  93. #endif