ConstructedOctetStream.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  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;
  5. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO;
  6. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1
  7. {
  8. internal class ConstructedOctetStream
  9. : BaseInputStream
  10. {
  11. private readonly Asn1StreamParser _parser;
  12. private bool _first = true;
  13. private Stream _currentStream;
  14. internal ConstructedOctetStream(
  15. Asn1StreamParser parser)
  16. {
  17. _parser = parser;
  18. }
  19. public override int Read(byte[] buffer, int offset, int count)
  20. {
  21. if (_currentStream == null)
  22. {
  23. if (!_first)
  24. return 0;
  25. Asn1OctetStringParser next = GetNextParser();
  26. if (next == null)
  27. return 0;
  28. _first = false;
  29. _currentStream = next.GetOctetStream();
  30. }
  31. int totalRead = 0;
  32. for (;;)
  33. {
  34. int numRead = _currentStream.Read(buffer, offset + totalRead, count - totalRead);
  35. if (numRead > 0)
  36. {
  37. totalRead += numRead;
  38. if (totalRead == count)
  39. return totalRead;
  40. }
  41. else
  42. {
  43. Asn1OctetStringParser next = GetNextParser();
  44. if (next == null)
  45. {
  46. _currentStream = null;
  47. return totalRead;
  48. }
  49. _currentStream = next.GetOctetStream();
  50. }
  51. }
  52. }
  53. public override int ReadByte()
  54. {
  55. if (_currentStream == null)
  56. {
  57. if (!_first)
  58. return 0;
  59. Asn1OctetStringParser next = GetNextParser();
  60. if (next == null)
  61. return 0;
  62. _first = false;
  63. _currentStream = next.GetOctetStream();
  64. }
  65. for (;;)
  66. {
  67. int b = _currentStream.ReadByte();
  68. if (b >= 0)
  69. return b;
  70. Asn1OctetStringParser next = GetNextParser();
  71. if (next == null)
  72. {
  73. _currentStream = null;
  74. return -1;
  75. }
  76. _currentStream = next.GetOctetStream();
  77. }
  78. }
  79. private Asn1OctetStringParser GetNextParser()
  80. {
  81. IAsn1Convertible asn1Obj = _parser.ReadObject();
  82. if (asn1Obj == null)
  83. return null;
  84. if (asn1Obj is Asn1OctetStringParser)
  85. return (Asn1OctetStringParser)asn1Obj;
  86. throw new IOException("unknown object encountered: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(asn1Obj));
  87. }
  88. }
  89. }
  90. #pragma warning restore
  91. #endif