Search code examples
javaexceptionkeystore

How does one correctly create and access a KeyStore in java to store an encryption key?


I've been mixing and matching code, trying to learn by example for using KeyStores.

I have this createKeyStore method:

private static KeyStore createKeyStore(String fileName, String pw) throws Exception
    {
        File file = new File(fileName);

        final KeyStore keyStore = KeyStore.getInstance("JCEKS");
        if (file.exists())
        {
            // .keystore file already exists => load it
            keyStore.load(new FileInputStream(file), pw.toCharArray());
        }
        else
        {
            // .keystore file not created yet => create it
            keyStore.load(null, null);
            keyStore.store(new FileOutputStream(fileName), pw.toCharArray());
        }

        return keyStore;
    }`

It seems to work, no errors are thrown.

I am then trying to access the code by:

KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    keystore.load(new FileInputStream(keystorePath), pass.toCharArray());

    String alias = "alias";
    char[] password = pass.toCharArray();

    Certificate cert = keystore.getCertificate(alias);
    keystore.setCertificateEntry(alias, cert);

    // Save the new keystore contents
    FileOutputStream out = new FileOutputStream(keystoreFile);
    keystore.store(out, password);
    out.close();

But my call to keystore.load throws an Invalid Keystore Format exception. I tried to replace the FileInputStream with null, but it seems to throw an error setting the certificate.

TL;DR: I am only trying to store a few encryption keys in this keystore, but I can't seem to access it correctly.

Thanks for reading!


Solution

  • You have:

    final KeyStore keyStore = KeyStore.getInstance("JCEKS");
    

    and

    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    

    Change these so they agree.

    This:

    Certificate cert = keystore.getCertificate(alias);
    keystore.setCertificateEntry(alias, cert);
    

    is pointless. If there wasn't such a certificate in the keystore, it will fail, and if there was, it will just replace it with itself. What's the point exactly?

    I tried to replace the FileInputStream with null

    I cannot imagine why. There's nothing in the Javadoc that suggests that will work.