javax509certificatekeystorep7b

How to read a p7b file programmatically in java


I have .p7b file in my local storage (C:\Users\Certs\cert.p7b). This solution is not working for me.

I tried the following.

File file = new File("C:\Users\Certs\cert.p7b");
BufferedInputStream bis = null;
try {
     byte[] buffer = new byte[(int) file.length()];
     DataInputStream in = new DataInputStream(new FileInputStream(file));
     in.readFully(buffer);
     in.close();
     CertificateFactory certificatefactory = CertificateFactory.getInstance("X.509");
     X509Certificate cert = certificatefactory.getCertificate(in);
}catch (Exception e){
     System.out.println("Exception");
}

But it is not working. So how can I load this .p7b file and then store it in a keystore.


Solution

  • To read the certificates out of PKCS#7 file, you can use this code snippet:

    public static final Certificate[] readCertificatesFromPKCS7(byte[] binaryPKCS7Store) throws Exception
    {
        try (ByteArrayInputStream bais = new ByteArrayInputStream(binaryPKCS7Store);)
        {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            Collection<?> c = cf.generateCertificates(bais);
    
            List<Certificate> certList = new ArrayList<Certificate>();
    
            if (c.isEmpty())
            {
                // If there are now certificates found, the p7b file is probably not in binary format.
                // It may be in base64 format.
                // The generateCertificates method only understands raw data.
            }
            else
            {
    
                Iterator<?> i = c.iterator();
    
                while (i.hasNext())
                {
                    certList.add((Certificate) i.next());
                }
            }
    
            java.security.cert.Certificate[] certArr = new java.security.cert.Certificate[certList.size()];
    
            return certList.toArray(certArr);
        }
    }