summaryrefslogtreecommitdiff
path: root/bcprov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/PEMUtil.java
blob: 36c715937efac1c090bc7dc338e61b44bbc449e4 (plain)
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
package org.bouncycastle.jcajce.provider.asymmetric.x509;

import java.io.IOException;
import java.io.InputStream;

import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.util.encoders.Base64;

class PEMUtil
{
    /**
     * Boundary class. Keeps track of the required header/footer pair for the
     * current PEM object.
     *
     */
    private class Boundaries
    {
        private final String _header;
        private final String _footer;

        private Boundaries(String type)
        {
            this._header = "-----BEGIN " + type + "-----";
            this._footer = "-----END " + type + "-----";
        }

        public boolean isTheExpectedHeader(String line)
        {
            return line.startsWith(_header);
        }

        public boolean isTheExpectedFooter(String line)
        {
            return line.startsWith(_footer);
        }
    }

    private final Boundaries[] _supportedBoundaries;

    PEMUtil(String type)
    {
        _supportedBoundaries = new Boundaries[]
        { new Boundaries(type), new Boundaries("X509 " + type),
                new Boundaries("PKCS7") };
    }

    private String readLine(InputStream in) throws IOException
    {
        int c;
        StringBuffer l = new StringBuffer();

        do
        {
            while (((c = in.read()) != '\r') && c != '\n' && (c >= 0))
            {
                l.append((char) c);
            }
        }
        while (c >= 0 && l.length() == 0);
   
        if (c < 0)
        {
            // make sure to return the read bytes if the end of file is encountered
            if (l.length() == 0)
            {
                return null;
            }
            return l.toString();
        }

        // make sure we parse to end of line.
        if (c == '\r')
        {
            // a '\n' may follow
            in.mark(1);
            if (((c = in.read()) == '\n'))
            {
                in.mark(1);
            }

            if (c > 0)
            {
                in.reset();
            }
        }

        return l.toString();
    }

    /**
     * Returns a {@link Boundaries} object representing the passed in boundary
     * string.
     * 
     * @param line the boundary string
     * @return the {@link Boundaries} object corresponding to the given boundary
     *         string or <code>null</code> if the passed in string is not a valid
     *         boundary.
     */
    private Boundaries getBoundaries(String line)
    {
        for (int i = 0; i != _supportedBoundaries.length; i++)
        {
            Boundaries boundary = _supportedBoundaries[i];
            
            if (boundary.isTheExpectedHeader(line) || boundary.isTheExpectedFooter(line))
            {
                return boundary;
            }
        }

        return null;
    }

    ASN1Sequence readPEMObject(
        InputStream in)
        throws IOException
    {
        String line;
        StringBuffer pemBuf = new StringBuffer();

        Boundaries header = null;

        while (header == null && (line = readLine(in)) != null)
        {
            header = getBoundaries(line);
            if (header != null && !header.isTheExpectedHeader(line))
            {
                throw new IOException("malformed PEM data: found footer where header was expected");
            }
        }

        if (header == null)
        {
            throw new IOException("malformed PEM data: no header found");
        }

        Boundaries footer = null;

        while (footer == null && (line = readLine(in)) != null)
        {
            footer = getBoundaries(line);
            if (footer != null)
            {
                if (!header.isTheExpectedFooter(line))
                {
                    throw new IOException("malformed PEM data: header/footer mismatch");
                }
            }
            else
            {
                pemBuf.append(line);
            }
        }

        if (footer == null)
        {
            throw new IOException("malformed PEM data: no footer found");
        }

        if (pemBuf.length() != 0)
        {
            try
            {
                return ASN1Sequence.getInstance(Base64.decode(pemBuf.toString()));
            }
            catch (Exception e)
            {
                throw new IOException("malformed PEM data encountered");
            }
        }

        return null;
    }
}