01: package org.bouncycastle.jce.provider;
02:
03: import org.bouncycastle.asn1.ASN1InputStream;
04: import org.bouncycastle.asn1.ASN1Sequence;
05: import org.bouncycastle.asn1.DERObject;
06: import org.bouncycastle.util.encoders.Base64;
07:
08: import java.io.IOException;
09: import java.io.InputStream;
10:
11: public class PEMUtil {
12: private final String _header1;
13: private final String _header2;
14: private final String _footer1;
15: private final String _footer2;
16:
17: PEMUtil(String type) {
18: _header1 = "-----BEGIN " + type + "-----";
19: _header2 = "-----BEGIN X509 " + type + "-----";
20: _footer1 = "-----END " + type + "-----";
21: _footer2 = "-----END X509 " + type + "-----";
22: }
23:
24: private String readLine(InputStream in) throws IOException {
25: int c;
26: StringBuffer l = new StringBuffer();
27:
28: do {
29: while (((c = in.read()) != '\r') && c != '\n' && (c >= 0)) {
30: if (c == '\r') {
31: continue;
32: }
33:
34: l.append((char) c);
35: }
36: } while (c >= 0 && l.length() == 0);
37:
38: if (c < 0) {
39: return null;
40: }
41:
42: return l.toString();
43: }
44:
45: ASN1Sequence readPEMObject(InputStream in) throws IOException {
46: String line;
47: StringBuffer pemBuf = new StringBuffer();
48:
49: while ((line = readLine(in)) != null) {
50: if (line.equals(_header1) || line.equals(_header2)) {
51: break;
52: }
53: }
54:
55: while ((line = readLine(in)) != null) {
56: if (line.equals(_footer1) || line.equals(_footer2)) {
57: break;
58: }
59:
60: pemBuf.append(line);
61: }
62:
63: if (pemBuf.length() != 0) {
64: DERObject o = new ASN1InputStream(Base64.decode(pemBuf
65: .toString())).readObject();
66: if (!(o instanceof ASN1Sequence)) {
67: throw new IOException("malformed PEM data encountered");
68: }
69:
70: return (ASN1Sequence) o;
71: }
72:
73: return null;
74: }
75: }
|