PemReader.java revision e6bf3e8dfa2804891a82075cb469b736321b4827
1package org.bouncycastle.util.io.pem;
2
3import java.io.BufferedReader;
4import java.io.IOException;
5import java.io.Reader;
6import java.util.ArrayList;
7import java.util.List;
8
9import org.bouncycastle.util.encoders.Base64;
10
11public class PemReader
12    extends BufferedReader
13{
14    private static final String BEGIN = "-----BEGIN ";
15    private static final String END = "-----END ";
16
17    public PemReader(Reader reader)
18    {
19        super(reader);
20    }
21
22    public PemObject readPemObject()
23        throws IOException
24    {
25        String line = readLine();
26
27        while (line != null && !line.startsWith(BEGIN))
28        {
29            line = readLine();
30        }
31
32        if (line != null)
33        {
34            line = line.substring(BEGIN.length());
35            int index = line.indexOf('-');
36            String type = line.substring(0, index);
37
38            if (index > 0)
39            {
40                return loadObject(type);
41            }
42        }
43
44        return null;
45    }
46
47    private PemObject loadObject(String type)
48        throws IOException
49    {
50        String          line;
51        String          endMarker = END + type;
52        StringBuffer    buf = new StringBuffer();
53        List            headers = new ArrayList();
54
55        while ((line = readLine()) != null)
56        {
57            if (line.indexOf(":") >= 0)
58            {
59                int index = line.indexOf(':');
60                String hdr = line.substring(0, index);
61                String value = line.substring(index + 1).trim();
62
63                headers.add(new PemHeader(hdr, value));
64
65                continue;
66            }
67
68            if (line.indexOf(endMarker) != -1)
69            {
70                break;
71            }
72
73            buf.append(line.trim());
74        }
75
76        if (line == null)
77        {
78            throw new IOException(endMarker + " not found");
79        }
80
81        return new PemObject(type, headers, Base64.decode(buf.toString()));
82    }
83
84}
85