PemReader.cs 2.2 KB

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