PKCS12 Java Keystore from CA and User certificate in java

六月ゝ 毕业季﹏ 提交于 2019-11-27 14:05:08

The PKCS#12 format is intended for storing a private key associated with a certificate chain, and both are required (although you might not need the whole chain). Although the PKCS12 keystore type does a good job for mapping this format to a Java KeyStore, not everything is supported for this reason.

What you're trying to do in your first attempt is storing a certificate on its own, which won't work.

What you're trying to do in your second attempt (ks.setKeyEntry("SomeAlias", userCert.getPublicKey().getEncoded(), chain)) is to for a public key in place of what should be a private key (see KeyStore#setKeyEntry).

.cer file tend to be just for certificates not private keys (although of course, the extension is ultimately just an indication). If you export your .cer file from Keychain Access.app, you won't get the private key with it (that's what the .p12 export format is for).

EDIT about KeychainStore:

If the reason you're trying to do this conversion is ultimately to access private keys and certificates that are already in the keychain you could load them from the KeychainStore directly:

KeyStore ks = KeyStore.getInstance("KeychainStore", "Apple");
ks.load(null, "-".toCharArray());

A couple of notes for this:

  • Any non-null, non-empty password will do to use the private key (e.g. "-".toCharArray()), as access will be prompted by the OS's security service (like it would in other applications).
  • As far as I'm aware, there is still a bug and it only allows access to one private key/certificate pair (even if a number of pairs of private key/certificate pairs are present in the keychain)

http://www.docjar.com/html/api/org/bouncycastle/jce/examples/PKCS12Example.java.html

This is how to add a certificate with a associating private key to a PKCS12 keystore. When you are using client authentication, the keystore needs to contain also the private key, in that case you use KeyStore.getInstance("PKCS12").

When youre not using client authentication but only server authentication(and private key will not be added to keystore, since it belongs to the server), its better to use KeyStore.getInstance("JKS"), than you can add multiple certificates with an alias to that one keystore.

When you are using PKCS12, as far as I know, you can only add 1 certificate(you have to add the whole certificate chain) associated with the private key, you want to use for that certificate.

I'm a couple years late to the party but this took me a few hours to get working correctly, so I thought it was worth posting a working solution. This solution uses 1) A .p12 / PKCS12 certificate and 2) a CA not in the default TrustManager (and you want to add it programatically rather than adding to the default TrustManager). 3) No third party cryptography libraries, just HttpClient to bring it all together.

I've also added a few helpful keytool and openssl commands in the JavaDoc for working with certificates, as that is an art in itself.

// Stitch it all together with HttpClient
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(getSSLSocketFactory()).build();


private SSLConnectionSocketFactory getSSLSocketFactory() {
    try {
        SSLContext sslContext = SSLContext.getInstance("TLS");

        KeyManager[] keyManager = getKeyManager("pkcs12", "path/to/cert.p12"), "p12_password"));
        TrustManager[] trustManager = getTrustManager("jks", "path/to/CA.truststore", "trust_store_password"));
        sslContext.init(keyManager, trustManager, new SecureRandom());

        return new SSLConnectionSocketFactory(sslContext);
    } catch (Exception e) {
        throw new RuntimeException("Unable to setup keystore and truststore", e);
    }
}

/**
 * Some useful commands for looking at the client certificate and private key:
 * keytool -keystore certificate.p12 -list -storetype pkcs12 -v
 * openssl pkcs12 -info -in certificate.p12
 */
private KeyManager[] getKeyManager(String keyStoreType, String keyStoreFile, String keyStorePassword) throws Exception {
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyStore.load(this.getClass().getClassLoader().getResourceAsStream(keyStoreFile), keyStorePassword.toCharArray());
    kmf.init(keyStore, keyStorePassword.toCharArray());

    return kmf.getKeyManagers();
}

/**
 * Depending on what format (pem / cer / p12) you have received the CA in, you will need to use a combination of openssl and keytool
 * to convert it to JKS format in order to be loaded into the truststore using the method below. 
 *
 * You could of course use keytool to import this into the JREs TrustStore - my situation mandated I create it on the fly.
 *
 * Useful command to look at the CA certificate:
 * keytool -keystore root_ca.truststore -list -storetype jks -v
 *
 */
private TrustManager[] getTrustManager(String trustStoreType, String trustStoreFile, String trustStorePassword) throws Exception {
    KeyStore trustStore = KeyStore.getInstance(trustStoreType);
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustStore.load(this.getClass().getClassLoader().getResourceAsStream(trustStoreFile), trustStorePassword.toCharArray());
    tmf.init(trustStore);

    return tmf.getTrustManagers();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!