summary refs log tree commit diff
path: root/crypto/src/util/io/pem/PemReader.cs
blob: 6e27a3749f24e45d9e9024a070f0bf9a0a951bc4 (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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

using Org.BouncyCastle.Utilities.Encoders;

namespace Org.BouncyCastle.Utilities.IO.Pem
{
	public class PemReader
		: IDisposable
	{
        private const int LineLength = 64;

        private readonly TextReader m_reader;
		private readonly MemoryStream m_buffer;
		private readonly StreamWriter m_textBuffer;
		private readonly Stack<int> m_pushback = new Stack<int>();

		public PemReader(TextReader reader)
		{
			m_reader = reader ?? throw new ArgumentNullException(nameof(reader));
            m_buffer = new MemoryStream();
            m_textBuffer = new StreamWriter(m_buffer);
		}

        #region IDisposable

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                m_reader.Dispose();
            }
        }

        #endregion

        public TextReader Reader 
		{
			get { return m_reader; }
		}


		/// <returns>
		/// A <see cref="PemObject"/>
		/// </returns>
		/// <exception cref="IOException"></exception>	
		public PemObject ReadPemObject()
        {
			//
			// Look for BEGIN
			//

			for (;;)
			{
				// Seek a leading dash, ignore anything up to that point.
				if (!SeekDash())
					return null; 

				// consume dash [-----]BEGIN ...
				if (!ConsumeDash())
					throw new IOException("no data after consuming leading dashes");

				SkipWhiteSpace();

				if (Expect("BEGIN"))
					break;
			}

			SkipWhiteSpace();

			//
			// Consume type, accepting whitespace
			//

			if (!BufferUntilStopChar('-', false))
				throw new IOException("ran out of data before consuming type");

			string type = BufferedString().Trim();

			// Consume dashes after type.

			if (!ConsumeDash())
				throw new IOException("ran out of data consuming header");

			SkipWhiteSpace();

			//
			// Read ahead looking for headers.
			// Look for a colon for up to 64 characters, as an indication there might be a header.
			//

			var headers = new List<PemHeader>();

			while (SeekColon(LineLength))
            {
				if (!BufferUntilStopChar(':', false))
					throw new IOException("ran out of data reading header key value");

				string key = BufferedString().Trim();

				int c = Read();
				if (c != ':')
					throw new IOException("expected colon");

				//
				// We are going to look for well formed headers, if they do not end with a "LF" we cannot
				// discern where they end.
				//

				if (!BufferUntilStopChar('\n', false)) // Now read to the end of the line.
					throw new IOException("ran out of data before consuming header value");

				SkipWhiteSpace();

				string value = BufferedString().Trim();
				headers.Add(new PemHeader(key, value));
			}

			//
			// Consume payload, ignoring all white space until we encounter a '-'
			//

			SkipWhiteSpace();

			if (!BufferUntilStopChar('-', true))
				throw new IOException("ran out of data before consuming payload");

			string payload = BufferedString();

			// Seek the start of the end.
			if (!SeekDash())
				throw new IOException("did not find leading '-'");

			if (!ConsumeDash())
				throw new IOException("no data after consuming trailing dashes");

			if (!Expect("END " + type))
				throw new IOException("END " + type + " was not found.");

			if (!SeekDash())
				throw new IOException("did not find ending '-'");

			// consume trailing dashes.
			ConsumeDash();

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

		private string BufferedString()
        {
			m_textBuffer.Flush();

#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
            if (!m_buffer.TryGetBuffer(out var data))
                throw new InvalidOperationException();

            string value = Encoding.UTF8.GetString(data);
#else
            string value = Strings.FromUtf8ByteArray(m_buffer.ToArray());
#endif

            m_buffer.Position = 0;
			m_buffer.SetLength(0);

			return value;
        }

		private bool SeekDash()
        {
			int c;
			while ((c = Read()) >= 0)
            {
				if (c == '-')
					break;
            }

			PushBack(c);

			return c >= 0;
        }

		/// <summary>
		/// Seek ':" up to the limit.
		/// </summary>
		/// <param name="upTo"></param>
		/// <returns></returns>
		private bool SeekColon(int upTo)
		{
			int c = 0;
			bool colonFound = false;
			var read = new List<int>();

			for (; upTo >= 0 && c >= 0; upTo--)
            {
				c = Read();
				read.Add(c);
				if (c == ':')
                {
					colonFound = true;
					break;
                }
            }

			int readPos = read.Count;
			while (--readPos >= 0)
			{
				PushBack(read[readPos]);
			}

			return colonFound;
		}

		/// <summary>
		/// Consume the dashes
		/// </summary>
		/// <returns></returns>
		private bool ConsumeDash()
        {
			int c;
			while ((c = Read()) >= 0)
			{
				if (c != '-')
					break;
			}

			PushBack(c);

			return c >= 0;
		}

		/// <summary>
		/// Skip white space leave char in stream.
		/// </summary>
		private void SkipWhiteSpace()
        {
			int c;
			while ((c = Read()) >= 0)
			{
				if (c > ' ')
					break;
			}

			PushBack(c);
		}

		/// <summary>
		/// Read forward consuming the expected string.
		/// </summary>
		/// <param name="value">expected string</param>
		/// <returns>false if not consumed</returns>
		private bool Expect(string value)
        {
			for (int t = 0; t < value.Length; t++)
            {
				if (Read() != value[t])
					return false;
            }

			return true;
        }

		/// <summary>
		/// Consume until dash.
		/// </summary>
		/// <returns>true if stream end not met</returns>
		private bool BufferUntilStopChar(char stopChar, bool skipWhiteSpace)
        {
			int c;
			while ((c = Read()) >= 0)
			{	
				if (skipWhiteSpace && c <= ' ')
					continue;

				if (c == stopChar)
				{
                    PushBack(c);
                    break;
                }

				m_textBuffer.Write((char)c);
				m_textBuffer.Flush();
			}

			return c >= 0;
		}

		private void PushBack(int value)
        {
			m_pushback.Push(value);
        }

		private int Read()
        {
			if (m_pushback.Count > 0)
				return m_pushback.Pop();

			return m_reader.Read();
        }
	}
}