PEMParser.cs 2.1 KB

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