1package org.bouncycastle.jcajce.provider.asymmetric.x509;
2
3import java.io.IOException;
4import java.io.InputStream;
5
6import org.bouncycastle.asn1.ASN1Sequence;
7import org.bouncycastle.util.encoders.Base64;
8
9class PEMUtil
10{
11    private final String _header1;
12    private final String _header2;
13    private final String _footer1;
14    private final String _footer2;
15
16    PEMUtil(
17        String type)
18    {
19        _header1 = "-----BEGIN " + type + "-----";
20        _header2 = "-----BEGIN X509 " + type + "-----";
21        _footer1 = "-----END " + type + "-----";
22        _footer2 = "-----END X509 " + type + "-----";
23    }
24
25    private String readLine(
26        InputStream in)
27        throws IOException
28    {
29        int             c;
30        StringBuffer l = new StringBuffer();
31
32        do
33        {
34            while (((c = in.read()) != '\r') && c != '\n' && (c >= 0))
35            {
36                l.append((char)c);
37            }
38        }
39        while (c >= 0 && l.length() == 0);
40
41        if (c < 0)
42        {
43            return null;
44        }
45
46        // make sure we parse to end of line.
47        if (c == '\r')
48        {
49            // a '\n' may follow
50            in.mark(1);
51            if (((c = in.read()) == '\n'))
52            {
53                in.mark(1);
54            }
55
56            if (c > 0)
57            {
58                in.reset();
59            }
60        }
61
62        return l.toString();
63    }
64
65    ASN1Sequence readPEMObject(
66        InputStream in)
67        throws IOException
68    {
69        String line;
70        StringBuffer pemBuf = new StringBuffer();
71
72        while ((line = readLine(in)) != null)
73        {
74            if (line.startsWith(_header1) || line.startsWith(_header2))
75            {
76                break;
77            }
78        }
79
80        while ((line = readLine(in)) != null)
81        {
82            if (line.startsWith(_footer1) || line.startsWith(_footer2))
83            {
84                break;
85            }
86
87            pemBuf.append(line);
88        }
89
90        if (pemBuf.length() != 0)
91        {
92            try
93            {
94                return ASN1Sequence.getInstance(Base64.decode(pemBuf.toString()));
95            }
96            catch (Exception e)
97            {
98                throw new IOException("malformed PEM data encountered");
99            }
100        }
101
102        return null;
103    }
104}
105