0
votes

I need to support the same functionality of Keytool.exe to convert java keystore to PFX file through programming by using KeyTool class. I cant use command prompt process from my application due to the project requirement limitation so through programming i cannot open command process either.

e.g.

C:\keytool -importkeystore -srckeystore .k eystore -srcstoretype JKS -destkeystore thekeystore.pfx -deststoretype PKCS12

I can create PFX file by keytool.exe by using above command but my requirement is to generate the PFX file by the keystore from my own application. I searched a lot on google and i could not find any helpful link which can give any reference or help regarding this issue. There is a class sun.security.tools.Keytool i searched this as well but i am not able to find any general programming help for this class. Kindly if someone has any tip or idea then share it.

1

1 Answers

2
votes

I don't know about the KeyTool class, and since it's not a public API I'd be averse to using it, but you can read and write keystores yourself using the KeyStore class. According to the documentation, Java supports, at a minimum, the jks and pkcs12 keystore types, so you can do something like:

public void convertKeystore(Path sourceKeystorePath,
                            char[] sourceKeystorePassword,
                            Path destKeystorePath,
                            char[] destKeystorePassword)
throws GeneralSecurityException, IOException {

    KeyStore sourceKeystore = KeyStore.getInstance("jks");
    try (InputStream stream =
            new BufferedInputStream(
                Files.newInputStream(sourceKeystorePath))) {
        sourceKeystore.load(stream, sourceKeystorePassword);
    }

    KeyStore destKeystore = KeyStore.getInstance("pkcs12");
    destKeystore.load(null, destKeystorePassword);

    // Assume each alias in a keystore has the same password
    // as the keystore itself.
    KeyStore.ProtectionParameter sourceAliasPassword =
        new KeyStore.PasswordProtection(sourceKeystorePassword);
    KeyStore.ProtectionParameter destAliasPassword =
        new KeyStore.PasswordProtection(destKeystorePassword);

    Enumeration<String> aliasList = sourceKeystore.aliases();
    while (aliasList.hasMoreElements()) {
        String alias = aliasList.nextElement();
        KeyStore.Entry entry =
            sourceKeystore.getEntry(alias, sourceAliasPassword);
        destKeystore.setEntry(alias, entry, destAliasPassword);
    }

    try (OutputStream stream =
            new BufferedOutputStream(
                Files.newOutputStream(destKeystorePath))) {
        destKeystore.store(stream, destKeystorePassword);
    }
}