DERGenerator.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System.IO;
  4. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO;
  5. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1
  6. {
  7. public abstract class DerGenerator
  8. : Asn1Generator
  9. {
  10. private bool _tagged = false;
  11. private bool _isExplicit;
  12. private int _tagNo;
  13. protected DerGenerator(
  14. Stream outStream)
  15. : base(outStream)
  16. {
  17. }
  18. protected DerGenerator(
  19. Stream outStream,
  20. int tagNo,
  21. bool isExplicit)
  22. : base(outStream)
  23. {
  24. _tagged = true;
  25. _isExplicit = isExplicit;
  26. _tagNo = tagNo;
  27. }
  28. private static void WriteLength(
  29. Stream outStr,
  30. int length)
  31. {
  32. if (length > 127)
  33. {
  34. int size = 1;
  35. int val = length;
  36. while ((val >>= 8) != 0)
  37. {
  38. size++;
  39. }
  40. outStr.WriteByte((byte)(size | 0x80));
  41. for (int i = (size - 1) * 8; i >= 0; i -= 8)
  42. {
  43. outStr.WriteByte((byte)(length >> i));
  44. }
  45. }
  46. else
  47. {
  48. outStr.WriteByte((byte)length);
  49. }
  50. }
  51. internal static void WriteDerEncoded(
  52. Stream outStream,
  53. int tag,
  54. byte[] bytes)
  55. {
  56. outStream.WriteByte((byte) tag);
  57. WriteLength(outStream, bytes.Length);
  58. outStream.Write(bytes, 0, bytes.Length);
  59. }
  60. internal void WriteDerEncoded(
  61. int tag,
  62. byte[] bytes)
  63. {
  64. if (_tagged)
  65. {
  66. int tagNum = _tagNo | Asn1Tags.ContextSpecific;
  67. if (_isExplicit)
  68. {
  69. int newTag = _tagNo | Asn1Tags.Constructed | Asn1Tags.ContextSpecific;
  70. MemoryStream bOut = new MemoryStream();
  71. WriteDerEncoded(bOut, tag, bytes);
  72. WriteDerEncoded(Out, newTag, bOut.ToArray());
  73. }
  74. else
  75. {
  76. if ((tag & Asn1Tags.Constructed) != 0)
  77. {
  78. tagNum |= Asn1Tags.Constructed;
  79. }
  80. WriteDerEncoded(Out, tagNum, bytes);
  81. }
  82. }
  83. else
  84. {
  85. WriteDerEncoded(Out, tag, bytes);
  86. }
  87. }
  88. internal static void WriteDerEncoded(
  89. Stream outStr,
  90. int tag,
  91. Stream inStr)
  92. {
  93. WriteDerEncoded(outStr, tag, Streams.ReadAll(inStr));
  94. }
  95. }
  96. }
  97. #pragma warning restore
  98. #endif