summary refs log tree commit diff
path: root/crypto/src/util/io/pem/PemReader.cs
blob: 77b4573389be581cbafa09883067e23be7fc0a3b (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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
using System;
using System.Collections.Generic;
using System.IO;

using Org.BouncyCastle.Utilities.Encoders;

namespace Org.BouncyCastle.Utilities.IO.Pem
{
	public class PemReader
		: IDisposable
	{		
		private readonly TextReader reader;
		private readonly MemoryStream buffer;
		private readonly StreamWriter textBuffer;
		private readonly List<int> pushback = new List<int>();
		int c = 0;

		public PemReader(TextReader reader)
		{
			this.reader = reader ?? throw new ArgumentNullException(nameof(reader));
            this.buffer = new MemoryStream();
            this.textBuffer = new StreamWriter(buffer);
		}

        #region IDisposable

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

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

        #endregion

        public TextReader Reader
		{
			get { return 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())
				{
					// There are no pem objects here.
					return null; 
				}


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


				skipWhiteSpace();


				if (!expect("BEGIN"))
				{
					continue;
				}

				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(64))
            {

				if (!bufferUntilStopChar(':',false))
                {
					throw new IOException("ran out of data reading header key value");
				}

				string key = bufferedString().Trim();


				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()
        {
			textBuffer.Flush();
			string value = Strings.FromUtf8ByteArray(buffer.ToArray());
			buffer.Position = 0;
			buffer.SetLength(0);
			return value;
        }


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

			PushBack(c);

			return c == '-';
        }


		/// <summary>
		/// Seek ':" up to the limit.
		/// </summary>
		/// <param name="upTo"></param>
		/// <returns></returns>
		private bool seekColon(int upTo)
		{
			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;
                }
            }

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

			return colonFound;
		}



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

			PushBack(c);

			return c != -1;
		}

		/// <summary>
		/// Skip white space leave char in stream.
		/// </summary>
		private void skipWhiteSpace()
        {
			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++)
            {
				c = Read();
				if (c == value[t])
                {
					continue;
                } else
                {
					return false;
                }
            }

			return true;
        }

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

				if (c != stopChar)
				{
					textBuffer.Write((char)c);
					textBuffer.Flush();
					
				} else
                {
					  PushBack(c);
					break;
                }
			}
			
			return c > -1;
		}

		private void PushBack(int value)
        {
			if (pushback.Count == 0)
            {
				pushback.Add(value);
            } else
            {
				pushback.Insert(0, value);
            }
        }

		private int Read()
        {
			if (pushback.Count > 0)
            {
				int i = pushback[0];
				pushback.RemoveAt(0);
				return i;
            }

			return reader.Read();
        }
	}
}