1 package org.bouncycastle.util.io.pem; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.Reader; 6 import java.util.ArrayList; 7 import java.util.List; 8 9 import org.bouncycastle.util.encoders.Base64; 10 11 public class PemReader 12 extends BufferedReader 13 { 14 private static final String BEGIN = "-----BEGIN "; 15 private static final String END = "-----END "; 16 17 public PemReader(Reader reader) 18 { 19 super(reader); 20 } 21 22 public PemObject readPemObject() 23 throws IOException 24 { 25 String line = readLine(); 26 27 if (line != null && line.startsWith(BEGIN)) 28 { 29 line = line.substring(BEGIN.length()); 30 int index = line.indexOf('-'); 31 String type = line.substring(0, index); 32 33 if (index > 0) 34 { 35 return loadObject(type); 36 } 37 } 38 39 return null; 40 } 41 42 private PemObject loadObject(String type) 43 throws IOException 44 { 45 String line; 46 String endMarker = END + type; 47 StringBuffer buf = new StringBuffer(); 48 List headers = new ArrayList(); 49 50 while ((line = readLine()) != null) 51 { 52 if (line.indexOf(":") >= 0) 53 { 54 int index = line.indexOf(':'); 55 String hdr = line.substring(0, index); 56 String value = line.substring(index + 1).trim(); 57 58 headers.add(new PemHeader(hdr, value)); 59 60 continue; 61 } 62 63 if (line.indexOf(endMarker) != -1) 64 { 65 break; 66 } 67 68 buf.append(line.trim()); 69 } 70 71 if (line == null) 72 { 73 throw new IOException(endMarker + " not found"); 74 } 75 76 return new PemObject(type, headers, Base64.decode(buf.toString())); 77 } 78 79 } 80