Converting .cer to .jks using java

2019-07-20 07:15发布

问题:

I wanted to convert a file with a .cer extension to .jks file. Can somebody please help me with this? I googled it but did not get much information. Even a tutorial or link would is fine. I guess Java Key Store is used. Thanks.

回答1:

I use BouncyCastle library, latest version (1.51)

 String certificateString = textSerializer.readStringFromFile(context, certificateFileName); //CERT IN PEM
 X509CertificateHolder x509CertificateHolder = pemConverter.convertPEMtoX509CertificateHolder(certificateString);

PEMConverter is my own class and this method looks like this

public X509CertificateHolder convertPEMtoX509CertificateHolder(String certPEMData)
    throws IOException {
    PEMParser pemParser = new PEMParser(new StringReader(certPEMData));
    Object parsedObj = pemParser.readObject();
    if (parsedObj instanceof X509CertificateHolder) {
        X509CertificateHolder x509CertificateHolder = (X509CertificateHolder) parsedObj;
        return x509CertificateHolder;
    } else {
        System.out.println("The object " + parsedObj.toString() + " is not an X509CertificateHolder.");
    }
}

This gives you a BouncyCastle X509Certificate. You can convert this to JCE Certificate with the converter.

public X509Certificate convertToJceX509Certificate(X509CertificateHolder x509CertificateHolder) //java.security.cert.x509certificate
{
    try
    {
        return new JcaX509CertificateConverter()
            .setProvider(BouncyCastleProvider.PROVIDER_NAME)
            .getCertificate(x509CertificateHolder);
    }
    catch (CertificateException e)
    {
        log.error("Error during BC -> JCA conversion of Certificate.", e);
        throw new RuntimeException(e);
    }
}

Now you can use this to load it into a keystore

    KeyPair keyPair = this.keyPairReader.readKeyPairFromFile(context, keyPairFileName);
    PrivateKey privateKey = keyPair.getPrivate();

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try
    {
        KeyStore ks = KeyStore.getInstance("PKCS12", BouncyCastleProvider.PROVIDER_NAME);
        ks.load(null);
        ks.setKeyEntry("key-alias", (Key) privateKey, password.toCharArray(),
                       new java.security.cert.Certificate[] { certificate });
        ks.store(bos, password.toCharArray());
        bos.close();
        Log.d(PKCS12KeyStoreExporter.class.getName(), "Export to byte array complete.");
    }
    catch(...)
    {
        //...
    }
    return bos.toByteArray();

And this byte[] is your PKCS12 file. However, the only difference for JKS is to use the standard JCE provider, and to get a JKS instance KeyStore instead of the PKCS12 one.