Sunday, July 16, 2017

Writing a Key Pair with a Password

    public static void writeAsPem (String filename, String password, KeyPair keyPair) throws IOException {
        JcaPEMWriter pemWriter = null;

        try {
            FileWriter fileWriter = new FileWriter(filename);
            pemWriter = new JcaPEMWriter(fileWriter);
            JcePEMEncryptorBuilder builder = new JcePEMEncryptorBuilder(PEM_ENCRYPTION_ALGORITHM);
            builder.setProvider(new BouncyCastleProvider());
            pemWriter.writeObject(keyPair, builder.build(password.toCharArray()));
        } finally {
            Utils.closeIgnoreExceptions(pemWriter);
        }
    }

This should be easy but it isn't.  When I tried googling "java how to write a password protected key pair for openssl" I got, as my first result, "JAVA: How to save a private key in a pem file with password protection."  Note that this is for a private key, not a key pair. In fact there wasn't anything about key pairs on the first page. There also wasn't anything useful on the second page.

This is what I mean about Java being in a dark age when it comes to SSL - it is difficult to find out how to do the simplest things.


No comments:

Post a Comment

The release date for Miranda is now 9/30/2018