DerBitString.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.Diagnostics;
  5. using System.IO;
  6. using System.Text;
  7. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Math;
  8. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  9. namespace Best.HTTP.SecureProtocol.Org.BouncyCastle.Asn1
  10. {
  11. public class DerBitString
  12. : DerStringBase, Asn1BitStringParser
  13. {
  14. internal class Meta : Asn1UniversalType
  15. {
  16. internal static readonly Asn1UniversalType Instance = new Meta();
  17. private Meta() : base(typeof(DerBitString), Asn1Tags.BitString) { }
  18. internal override Asn1Object FromImplicitPrimitive(DerOctetString octetString)
  19. {
  20. return CreatePrimitive(octetString.GetOctets());
  21. }
  22. internal override Asn1Object FromImplicitConstructed(Asn1Sequence sequence)
  23. {
  24. return sequence.ToAsn1BitString();
  25. }
  26. }
  27. private static readonly char[] table
  28. = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
  29. /**
  30. * return a Bit string from the passed in object
  31. *
  32. * @exception ArgumentException if the object cannot be converted.
  33. */
  34. public static DerBitString GetInstance(object obj)
  35. {
  36. if (obj == null)
  37. return null;
  38. if (obj is DerBitString derBitString)
  39. return derBitString;
  40. if (obj is IAsn1Convertible asn1Convertible)
  41. {
  42. Asn1Object asn1Object = asn1Convertible.ToAsn1Object();
  43. if (asn1Object is DerBitString converted)
  44. return converted;
  45. }
  46. else if (obj is byte[] bytes)
  47. {
  48. try
  49. {
  50. return GetInstance(FromByteArray(bytes));
  51. }
  52. catch (IOException e)
  53. {
  54. throw new ArgumentException("failed to construct BIT STRING from byte[]: " + e.Message);
  55. }
  56. }
  57. throw new ArgumentException("illegal object in GetInstance: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj));
  58. }
  59. /**
  60. * return a Bit string from a tagged object.
  61. *
  62. * @param obj the tagged object holding the object we want
  63. * @param explicitly true if the object is meant to be explicitly
  64. * tagged false otherwise.
  65. * @exception ArgumentException if the tagged object cannot
  66. * be converted.
  67. */
  68. public static DerBitString GetInstance(Asn1TaggedObject obj, bool isExplicit)
  69. {
  70. Asn1Object o = obj.GetObject();
  71. if (isExplicit || o is DerBitString)
  72. {
  73. return GetInstance(o);
  74. }
  75. // Not copied because assumed to be a tagged implicit primitive from the parser
  76. return CreatePrimitive(((Asn1OctetString)o).GetOctets());
  77. }
  78. internal readonly byte[] contents;
  79. public DerBitString(byte data, int padBits)
  80. {
  81. if (padBits > 7 || padBits < 0)
  82. throw new ArgumentException("pad bits cannot be greater than 7 or less than 0", "padBits");
  83. this.contents = new byte[] { (byte)padBits, data };
  84. }
  85. public DerBitString(byte[] data)
  86. : this(data, 0)
  87. {
  88. }
  89. /**
  90. * @param data the octets making up the bit string.
  91. * @param padBits the number of extra bits at the end of the string.
  92. */
  93. public DerBitString(byte[] data, int padBits)
  94. {
  95. if (data == null)
  96. throw new ArgumentNullException("data");
  97. if (padBits < 0 || padBits > 7)
  98. throw new ArgumentException("must be in the range 0 to 7", "padBits");
  99. if (data.Length == 0 && padBits != 0)
  100. throw new ArgumentException("if 'data' is empty, 'padBits' must be 0");
  101. this.contents = Arrays.Prepend(data, (byte)padBits);
  102. }
  103. public DerBitString(int namedBits)
  104. {
  105. if (namedBits == 0)
  106. {
  107. this.contents = new byte[]{ 0 };
  108. return;
  109. }
  110. int bits = 32 - Integers.NumberOfLeadingZeros(namedBits);
  111. int bytes = (bits + 7) / 8;
  112. Debug.Assert(0 < bytes && bytes <= 4);
  113. byte[] data = new byte[1 + bytes];
  114. for (int i = 1; i < bytes; i++)
  115. {
  116. data[i] = (byte)namedBits;
  117. namedBits >>= 8;
  118. }
  119. Debug.Assert((namedBits & 0xFF) != 0);
  120. data[bytes] = (byte)namedBits;
  121. int padBits = 0;
  122. while ((namedBits & (1 << padBits)) == 0)
  123. {
  124. ++padBits;
  125. }
  126. Debug.Assert(padBits < 8);
  127. data[0] = (byte)padBits;
  128. this.contents = data;
  129. }
  130. public DerBitString(Asn1Encodable obj)
  131. : this(obj.GetDerEncoded())
  132. {
  133. }
  134. internal DerBitString(byte[] contents, bool check)
  135. {
  136. if (check)
  137. {
  138. if (null == contents)
  139. throw new ArgumentNullException("contents");
  140. if (contents.Length < 1)
  141. throw new ArgumentException("cannot be empty", "contents");
  142. int padBits = contents[0];
  143. if (padBits > 0)
  144. {
  145. if (contents.Length < 2)
  146. throw new ArgumentException("zero length data with non-zero pad bits", "contents");
  147. if (padBits > 7)
  148. throw new ArgumentException("pad bits cannot be greater than 7 or less than 0", "contents");
  149. }
  150. }
  151. this.contents = contents;
  152. }
  153. /**
  154. * Return the octets contained in this BIT STRING, checking that this BIT STRING really
  155. * does represent an octet aligned string. Only use this method when the standard you are
  156. * following dictates that the BIT STRING will be octet aligned.
  157. *
  158. * @return a copy of the octet aligned data.
  159. */
  160. public virtual byte[] GetOctets()
  161. {
  162. if (contents[0] != 0)
  163. throw new InvalidOperationException("attempt to get non-octet aligned data from BIT STRING");
  164. return Arrays.CopyOfRange(contents, 1, contents.Length);
  165. }
  166. public virtual byte[] GetBytes()
  167. {
  168. if (contents.Length == 1)
  169. return Asn1OctetString.EmptyOctets;
  170. int padBits = contents[0];
  171. byte[] rv = Arrays.CopyOfRange(contents, 1, contents.Length);
  172. // DER requires pad bits be zero
  173. rv[rv.Length - 1] &= (byte)(0xFF << padBits);
  174. return rv;
  175. }
  176. public virtual int PadBits
  177. {
  178. get { return contents[0]; }
  179. }
  180. /**
  181. * @return the value of the bit string as an int (truncating if necessary)
  182. */
  183. public virtual int IntValue
  184. {
  185. get
  186. {
  187. int value = 0, end = System.Math.Min(5, contents.Length - 1);
  188. for (int i = 1; i < end; ++i)
  189. {
  190. value |= (int)contents[i] << (8 * (i - 1));
  191. }
  192. if (1 <= end && end < 5)
  193. {
  194. int padBits = contents[0];
  195. byte der = (byte)(contents[end] & (0xFF << padBits));
  196. value |= (int)der << (8 * (end - 1));
  197. }
  198. return value;
  199. }
  200. }
  201. internal override IAsn1Encoding GetEncoding(int encoding)
  202. {
  203. int padBits = contents[0];
  204. if (padBits != 0)
  205. {
  206. int last = contents.Length - 1;
  207. byte lastBer = contents[last];
  208. byte lastDer = (byte)(lastBer & (0xFF << padBits));
  209. if (lastBer != lastDer)
  210. return new PrimitiveEncodingSuffixed(Asn1Tags.Universal, Asn1Tags.BitString, contents, lastDer);
  211. }
  212. return new PrimitiveEncoding(Asn1Tags.Universal, Asn1Tags.BitString, contents);
  213. }
  214. internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo)
  215. {
  216. int padBits = contents[0];
  217. if (padBits != 0)
  218. {
  219. int last = contents.Length - 1;
  220. byte lastBer = contents[last];
  221. byte lastDer = (byte)(lastBer & (0xFF << padBits));
  222. if (lastBer != lastDer)
  223. return new PrimitiveEncodingSuffixed(tagClass, tagNo, contents, lastDer);
  224. }
  225. return new PrimitiveEncoding(tagClass, tagNo, contents);
  226. }
  227. protected override int Asn1GetHashCode()
  228. {
  229. if (contents.Length < 2)
  230. return 1;
  231. int padBits = contents[0];
  232. int last = contents.Length - 1;
  233. byte lastDer = (byte)(contents[last] & (0xFF << padBits));
  234. int hc = Arrays.GetHashCode(contents, 0, last);
  235. hc *= 257;
  236. hc ^= lastDer;
  237. return hc;
  238. }
  239. protected override bool Asn1Equals(Asn1Object asn1Object)
  240. {
  241. DerBitString that = asn1Object as DerBitString;
  242. if (null == that)
  243. return false;
  244. byte[] thisContents = this.contents, thatContents = that.contents;
  245. int length = thisContents.Length;
  246. if (thatContents.Length != length)
  247. return false;
  248. if (length == 1)
  249. return true;
  250. int last = length - 1;
  251. for (int i = 0; i < last; ++i)
  252. {
  253. if (thisContents[i] != thatContents[i])
  254. return false;
  255. }
  256. int padBits = thisContents[0];
  257. byte thisLastDer = (byte)(thisContents[last] & (0xFF << padBits));
  258. byte thatLastDer = (byte)(thatContents[last] & (0xFF << padBits));
  259. return thisLastDer == thatLastDer;
  260. }
  261. public Stream GetBitStream()
  262. {
  263. return new MemoryStream(contents, 1, contents.Length - 1, false);
  264. }
  265. public Stream GetOctetStream()
  266. {
  267. int padBits = contents[0] & 0xFF;
  268. if (0 != padBits)
  269. throw new IOException("expected octet-aligned bitstring, but found padBits: " + padBits);
  270. return GetBitStream();
  271. }
  272. public Asn1BitStringParser Parser
  273. {
  274. get { return this; }
  275. }
  276. public override string GetString()
  277. {
  278. byte[] str = GetDerEncoded();
  279. StringBuilder buffer = Shared.PlatformSupport.Text.StringBuilderPool.Get(1 + str.Length * 2); //new StringBuilder(1 + str.Length * 2);
  280. buffer.Append('#');
  281. for (int i = 0; i != str.Length; i++)
  282. {
  283. uint u8 = str[i];
  284. buffer.Append(table[u8 >> 4]);
  285. buffer.Append(table[u8 & 0xF]);
  286. }
  287. return Shared.PlatformSupport.Text.StringBuilderPool.ReleaseAndGrab(buffer);
  288. }
  289. internal static DerBitString CreatePrimitive(byte[] contents)
  290. {
  291. int length = contents.Length;
  292. if (length < 1)
  293. throw new ArgumentException("truncated BIT STRING detected", "contents");
  294. int padBits = contents[0];
  295. if (padBits > 0)
  296. {
  297. if (padBits > 7 || length < 2)
  298. throw new ArgumentException("invalid pad bits detected", "contents");
  299. byte finalOctet = contents[length - 1];
  300. if (finalOctet != (byte)(finalOctet & (0xFF << padBits)))
  301. return new DLBitString(contents, false);
  302. }
  303. return new DerBitString(contents, false);
  304. }
  305. }
  306. }
  307. #pragma warning restore
  308. #endif