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