summary refs log tree commit diff
path: root/crypto/src/util/io/pem/PemReader.cs
blob: 7e6252b9be2b19ec1e36ba6222a018d219a6ef0e (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
using System;
using System.Collections;
using System.IO;
using System.Text;

using Org.BouncyCastle.Utilities.Encoders;

namespace Org.BouncyCastle.Utilities.IO.Pem
{
	public class PemReader
	{
		private const string BeginString = "-----BEGIN ";
		private const string EndString = "-----END ";

		private readonly TextReader reader;

		public PemReader(TextReader reader)
		{
			if (reader == null)
				throw new ArgumentNullException("reader");

			this.reader = reader;
		}

		public TextReader Reader
		{
			get { return reader; }
		}

		/// <returns>
		/// A <see cref="PemObject"/>
		/// </returns>
		/// <exception cref="IOException"></exception>
		public PemObject ReadPemObject()
		{
            string line = reader.ReadLine();

            while (line != null && !Platform.StartsWith(line, BeginString)) 
            {
                line = reader.ReadLine();
            }

            if (line != null)
            {
                line = line.Substring(BeginString.Length);
                int index = line.IndexOf('-');

                if (index > 0 && Platform.EndsWith(line, "-----") && (line.Length - index) == 5)
                {
                    string type = line.Substring(0, index);

                    return LoadObject(type);
                }
            }

            return null;
		}

		private PemObject LoadObject(string type)
		{
			string endMarker = EndString + type;
			IList headers = Platform.CreateArrayList();
			StringBuilder buf = new StringBuilder();

			string line;
			while ((line = reader.ReadLine()) != null)
			{
				int colonPos = line.IndexOf(':');
				if (colonPos >= 0)
				{
                    string hdr = line.Substring(0, colonPos);
                    string val = line.Substring(colonPos + 1).Trim();

                    headers.Add(new PemHeader(hdr, val));
                    continue;
				}

                if (Platform.IndexOf(line, endMarker) >= 0)
                    break;

                buf.Append(line.Trim());
            }

            if (line == null)
				throw new IOException(endMarker + " not found");

			return new PemObject(type, headers, Base64.Decode(buf.ToString()));
		}
	}
}