Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

keytool

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?

like image 948
felipeptcho Avatar asked Aug 15 '17 20:08

felipeptcho


People also ask

What is used to generate a keystore and key?

Use the standard JDK keytool utility to generate and load a new key and a self-signed certificate. When prompted, supply the certificate and password information. Doing so protects the keystore file and the keys within in the file.


1 Answers

Here's a nice Java function to generate self signed certificates programmatically (link):

private X509Certificate generateCertificate(String dn, KeyPair keyPair, int validity, String sigAlgName) throws GeneralSecurityException, IOException {
    PrivateKey privateKey = keyPair.getPrivate();

    X509CertInfo info = new X509CertInfo();

    Date from = new Date();
    Date to = new Date(from.getTime() + validity * 1000L * 24L * 60L * 60L);

    CertificateValidity interval = new CertificateValidity(from, to);
    BigInteger serialNumber = new BigInteger(64, new SecureRandom());
    X500Name owner = new X500Name(dn);
    AlgorithmId sigAlgId = new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid);

    info.set(X509CertInfo.VALIDITY, interval);
    info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(serialNumber));
    info.set(X509CertInfo.SUBJECT, owner);
    info.set(X509CertInfo.ISSUER, owner);
    info.set(X509CertInfo.KEY, new CertificateX509Key(keyPair.getPublic()));
    info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
    info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(sigAlgId));

    // Sign the cert to identify the algorithm that's used.
    X509CertImpl certificate = new X509CertImpl(info);
    certificate.sign(privateKey, sigAlgName);

    // Update the algorith, and resign.
    sigAlgId = (AlgorithmId) certificate.get(X509CertImpl.SIG_ALG);
    info.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, sigAlgId);
    certificate = new X509CertImpl(info);
    certificate.sign(privateKey, sigAlgName);

    return certificate;
}

You can use it to generate a certificate from your key pair and insert it into the certificate chain in order to make the setKeyEntry() method work:

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

        Certificate[] chain = {generateCertificate("cn=Unknown", keyPair, 365, "SHA256withRSA")};

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        keyStore.setKeyEntry("main", keyPair.getPrivate(), "654321".toCharArray(), chain);
        keyStore.store(fos, "123456".toCharArray());
    } catch (IOException | GeneralSecurityException e) {
        e.printStackTrace();
    }
}
like image 165
felipeptcho Avatar answered Sep 21 '22 23:09

felipeptcho