PEMParser.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) && (!UNITY_WEBGL || UNITY_EDITOR)
  2. using System;
  3. using System.IO;
  4. using System.Text;
  5. using Org.BouncyCastle.Asn1;
  6. using Org.BouncyCastle.Utilities;
  7. using Org.BouncyCastle.Utilities.Encoders;
  8. namespace Org.BouncyCastle.X509
  9. {
  10. class PemParser
  11. {
  12. private readonly string _header1;
  13. private readonly string _header2;
  14. private readonly string _footer1;
  15. private readonly string _footer2;
  16. internal PemParser(
  17. string type)
  18. {
  19. _header1 = "-----BEGIN " + type + "-----";
  20. _header2 = "-----BEGIN X509 " + type + "-----";
  21. _footer1 = "-----END " + type + "-----";
  22. _footer2 = "-----END X509 " + type + "-----";
  23. }
  24. private string ReadLine(
  25. Stream inStream)
  26. {
  27. int c;
  28. StringBuilder l = new StringBuilder();
  29. do
  30. {
  31. while (((c = inStream.ReadByte()) != '\r') && c != '\n' && (c >= 0))
  32. {
  33. if (c == '\r')
  34. {
  35. continue;
  36. }
  37. l.Append((char)c);
  38. }
  39. }
  40. while (c >= 0 && l.Length == 0);
  41. if (c < 0)
  42. {
  43. return null;
  44. }
  45. return l.ToString();
  46. }
  47. internal Asn1Sequence ReadPemObject(
  48. Stream inStream)
  49. {
  50. string line;
  51. StringBuilder pemBuf = new StringBuilder();
  52. while ((line = ReadLine(inStream)) != null)
  53. {
  54. if (Org.BouncyCastle.Utilities.Platform.StartsWith(line, _header1) || Org.BouncyCastle.Utilities.Platform.StartsWith(line, _header2))
  55. {
  56. break;
  57. }
  58. }
  59. while ((line = ReadLine(inStream)) != null)
  60. {
  61. if (Org.BouncyCastle.Utilities.Platform.StartsWith(line, _footer1) || Org.BouncyCastle.Utilities.Platform.StartsWith(line, _footer2))
  62. {
  63. break;
  64. }
  65. pemBuf.Append(line);
  66. }
  67. if (pemBuf.Length != 0)
  68. {
  69. Asn1Object o = Asn1Object.FromByteArray(Base64.Decode(pemBuf.ToString()));
  70. if (!(o is Asn1Sequence))
  71. {
  72. throw new IOException("malformed PEM data encountered");
  73. }
  74. return (Asn1Sequence) o;
  75. }
  76. return null;
  77. }
  78. }
  79. }
  80. #endif