summary refs log tree commit diff
path: root/crypto/src/x509/PEMParser.cs
blob: 28f28ee0a4006e3b7b1a6016fcef92b67c20f86e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
using System;
using System.IO;
using System.Text;

using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Encoders;

namespace Org.BouncyCastle.X509
{
	class PemParser
	{
		private readonly string _header1;
		private readonly string _header2;
		private readonly string _footer1;
		private readonly string _footer2;

		internal PemParser(
			string type)
		{
			_header1 = "-----BEGIN " + type + "-----";
			_header2 = "-----BEGIN X509 " + type + "-----";
			_footer1 = "-----END " + type + "-----";
			_footer2 = "-----END X509 " + type + "-----";
		}

		private string ReadLine(
			Stream inStream)
		{
			int c;
			StringBuilder l = new StringBuilder();

			do
			{
				while (((c = inStream.ReadByte()) != '\r') && c != '\n' && (c >= 0))
				{
					if (c == '\r')
					{
						continue;
					}

					l.Append((char)c);
				}
			}
			while (c >= 0 && l.Length == 0);

			if (c < 0)
			{
				return null;
			}

			return l.ToString();
		}

		internal Asn1Sequence ReadPemObject(
			Stream inStream)
		{
			string line;
			StringBuilder pemBuf = new StringBuilder();

			while ((line = ReadLine(inStream)) != null)
			{
                if (Platform.StartsWith(line, _header1) || Platform.StartsWith(line, _header2))
				{
					break;
				}
			}

			while ((line = ReadLine(inStream)) != null)
			{
                if (Platform.StartsWith(line, _footer1) || Platform.StartsWith(line, _footer2))
				{
					break;
				}

				pemBuf.Append(line);
			}

			if (pemBuf.Length != 0)
			{
				Asn1Object o = Asn1Object.FromByteArray(Base64.Decode(pemBuf.ToString()));

				if (!(o is Asn1Sequence))
				{
					throw new IOException("malformed PEM data encountered");
				}

				return (Asn1Sequence) o;
			}

			return null;
		}
	}
}