PemReader.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.Collections;
  5. using System.IO;
  6. using System.Text;
  7. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders;
  8. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO.Pem
  9. {
  10. public class PemReader
  11. {
  12. private const string BeginString = "-----BEGIN ";
  13. private const string EndString = "-----END ";
  14. private readonly TextReader reader;
  15. public PemReader(TextReader reader)
  16. {
  17. if (reader == null)
  18. throw new ArgumentNullException("reader");
  19. this.reader = reader;
  20. }
  21. public TextReader Reader
  22. {
  23. get { return reader; }
  24. }
  25. /// <returns>
  26. /// A <see cref="PemObject"/>
  27. /// </returns>
  28. /// <exception cref="IOException"></exception>
  29. public PemObject ReadPemObject()
  30. {
  31. string line = reader.ReadLine();
  32. if (line != null && BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(line, BeginString))
  33. {
  34. line = line.Substring(BeginString.Length);
  35. int index = line.IndexOf('-');
  36. string type = line.Substring(0, index);
  37. if (index > 0)
  38. return LoadObject(type);
  39. }
  40. return null;
  41. }
  42. private PemObject LoadObject(string type)
  43. {
  44. string endMarker = EndString + type;
  45. IList headers = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
  46. StringBuilder buf = new StringBuilder();
  47. string line;
  48. while ((line = reader.ReadLine()) != null
  49. && BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.IndexOf(line, endMarker) == -1)
  50. {
  51. int colonPos = line.IndexOf(':');
  52. if (colonPos == -1)
  53. {
  54. buf.Append(line.Trim());
  55. }
  56. else
  57. {
  58. // Process field
  59. string fieldName = line.Substring(0, colonPos).Trim();
  60. if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(fieldName, "X-"))
  61. {
  62. fieldName = fieldName.Substring(2);
  63. }
  64. string fieldValue = line.Substring(colonPos + 1).Trim();
  65. headers.Add(new PemHeader(fieldName, fieldValue));
  66. }
  67. }
  68. if (line == null)
  69. {
  70. throw new IOException(endMarker + " not found");
  71. }
  72. if (buf.Length % 4 != 0)
  73. {
  74. throw new IOException("base64 data appears to be truncated");
  75. }
  76. return new PemObject(type, headers, Base64.Decode(buf.ToString()));
  77. }
  78. }
  79. }
  80. #pragma warning restore
  81. #endif