How can I generate a key pair and insert it into a KeyStore programmatically (without using the Java KeyTool)?

Viewed 11789

I would like to generate a key pair and insert it into a Java KeyStore programmatically. I can use the command line to do exactly what I want, but how to do that using Java code?

Here is the command line:

keytool -genkeypair \
    -dname "cn=Unknown" \
    -alias main \
    -keyalg RSA \
    -keysize 4096 \
    -keypass 654321 \
    -keystore C:\\Users\\Felipe\\ks \
    -storepass 123456 \
    -validity 365

Here is the Java code I have so far:

public static void main(String[] args) {
    try (
        FileOutputStream fos = new FileOutputStream("C:\\Users\\Felipe\\ks");
    ) {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(4096, SecureRandom.getInstance("SHA1PRNG"));
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        Certificate[] chain = {};

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        keyStore.setKeyEntry("main", keyPair.getPrivate(), "654321".toCharArray(), chain); // Error: Private key must be accompanied by certificate chain
        keyStore.store(fos, "123456".toCharArray());
    } catch (NoSuchAlgorithmException | KeyStoreException | CertificateException | IOException e) {
        e.printStackTrace();
    }
}

But I keep getting the following error message: Private key must be accompanied by certificate chain.

I think I should create a certificate and insert it into the certificate array, but how to do that?

1 Answers
Related