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        return l.toString();
47    }
48
49    ASN1Sequence readPEMObject(
50        InputStream in)
51        throws IOException
52    {
53        String line;
54        StringBuffer pemBuf = new StringBuffer();
55
56        while ((line = readLine(in)) != null)
57        {
58            if (line.startsWith(_header1) || line.startsWith(_header2))
59            {
60                break;
61            }
62        }
63
64        while ((line = readLine(in)) != null)
65        {
66            if (line.startsWith(_footer1) || line.startsWith(_footer2))
67            {
68                break;
69            }
70
71            pemBuf.append(line);
72        }
73
74        if (pemBuf.length() != 0)
75        {
76            try
77            {
78                return ASN1Sequence.getInstance(Base64.decode(pemBuf.toString()));
79            }
80            catch (Exception e)
81            {
82                throw new IOException("malformed PEM data encountered");
83            }
84        }
85
86        return null;
87    }
88}
89