DERGenerator.cs 2.5 KB

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