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 9public class 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 if (c == '\r') 37 { 38 continue; 39 } 40 41 l.append((char)c); 42 } 43 } 44 while (c >= 0 && l.length() == 0); 45 46 if (c < 0) 47 { 48 return null; 49 } 50 51 return l.toString(); 52 } 53 54 ASN1Sequence readPEMObject( 55 InputStream in) 56 throws IOException 57 { 58 String line; 59 StringBuffer pemBuf = new StringBuffer(); 60 61 while ((line = readLine(in)) != null) 62 { 63 if (line.startsWith(_header1) || line.startsWith(_header2)) 64 { 65 break; 66 } 67 } 68 69 while ((line = readLine(in)) != null) 70 { 71 if (line.startsWith(_footer1) || line.startsWith(_footer2)) 72 { 73 break; 74 } 75 76 pemBuf.append(line); 77 } 78 79 if (pemBuf.length() != 0) 80 { 81 try 82 { 83 return ASN1Sequence.getInstance(Base64.decode(pemBuf.toString())); 84 } 85 catch (Exception e) 86 { 87 throw new IOException("malformed PEM data encountered"); 88 } 89 } 90 91 return null; 92 } 93} 94