Java read certificate from file 

Joined:
04/09/2007
Posts:
727

May 17, 2011 21:14:58    Last update: May 17, 2011 21:17:58
  1. Read certificate one at a time from BufferedInputStream:
    // import java.security.cert.*;
    public void readCertificate(File f) throws Exception {
    	CertificateFactory cf = CertificateFactory.getInstance("X.509");
    
    	// Use BufferedInputStream (which supports mark and reset) so that each 
    	// generateCertificate call consumes one certificate.
    	BufferedInputStream in = new BufferedInputStream(new FileInputStream(f));
    	while (in.available() > 0) {
    	    Certificate cert = cf.generateCertificate(in);
    	    System.out.println("Cert:\n===================\n" + cert.toString() + "\n");
    	}
    	in.close();
    }
    

  2. Read all certificates from a file as a collection:
    public void readCertificates(File f) throws Exception {
    	CertificateFactory cf = CertificateFactory.getInstance("X.509");
    
    	InputStream in = new FileInputStream(f);
    	Collection<?extends Certificate> certs = cf.generateCertificates(in);
    	in.close();
    
    	for (Certificate cert: certs) {
    	    System.out.println("Cert:\n===================\n" + cert.toString() + "\n");
    	}
    }
    

Share |
| Comment  | Tags
 
Easy email testing with http://www.ximailstop.com