Showing posts with label openSSL. Show all posts
Showing posts with label openSSL. Show all posts

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.


Saturday, July 15, 2017

Weirdness with openSSL and Bouncy Castle

I spent most of the day trying to figure out why a private key wasn't loading only to find out that openSSL was behaving strangely.

I shouldn't put all the blame on openSSL, I was trying to use Bouncy Castle.

The problem appears to be that a file began with

-----BEGIN RSA PRIVATE KEY-----

instead of this

-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,913379F68EA66ADB

I would think that Bouncy Castle would detect this but apparently, I'm wrong.

Instead Bouncy Castle continues on its merry way, until it tries to get the decryption algorithm, at which point it throws the following exception:

org.bouncycastle.pkcs.PKCSException: unable to read encrypted data: unknown algorithm

Hence, my wasted day.

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