shred / acme4j

Java client for ACME (Let's Encrypt)
https://acme4j.shredzone.org
Apache License 2.0
521 stars 96 forks source link

Can only parse traditional files #139

Closed bomgar closed 1 year ago

bomgar commented 1 year ago

We call this code in our application:

KeyPairUtils.readKeyPair(reader)

It reads files generated by this command:

openssl genrsa -traditional -out private-key.pem 4096

Without the -traditional it causes problems:

    java.lang.ClassCastException: class org.bouncycastle.asn1.pkcs.PrivateKeyInfo cannot be cast to class org.bouncycastle.openssl.PEMKeyPair (org.bouncycastle.asn1.pkcs.PrivateKeyInfo and org.bouncycastle.openssl.PEMKeyPair are in unnamed module of loader 'app')
        at org.shredzone.acme4j.util.KeyPairUtils.readKeyPair(KeyPairUtils.java:105)
        at ...

The typecast here seems to be the problem:

PEMKeyPair keyPair = (PEMKeyPair) parser.readObject();
» openssl version
OpenSSL 3.0.8 7 Feb 2023 (Library: OpenSSL 3.0.8 7 Feb 2023)
shred commented 1 year ago

Without the -traditional parameter, openssl generates a private key in PKCS#8 format. The PEM file does not contain a public key. Generating a matching public key from that private key is out of scope for KeyPairUtils as a simple utility class. The main purpose of readKeyPair() is to read a PEM file that was written by writeKeyPair().

acme4j client itself only requires a standard java.security.KeyPair object. If you find a way to read a key pair from the PKCS#8 file, you can just use that KeyPair object.

bomgar commented 1 year ago

Ok thank you.

If anyone reads this and wants to know what I did (only works for RSA keys):

fun readKeyPair(r: Reader): KeyPair {
    PEMParser(r).use { parser ->
        return when(val o = parser.readObject()) {
            is PEMKeyPair -> {
                println("Read old style RSA PRIVATE KEY")
                JcaPEMKeyConverter().getKeyPair(o)
            }
            is PrivateKeyInfo -> {
                println("Read PRIVATE KEY. Assume it is RSA.")
                val privateKey = JcaPEMKeyConverter().getPrivateKey(o) as RSAPrivateCrtKey
                val spec = RSAPublicKeySpec(privateKey.modulus, privateKey.publicExponent)
                val publicKey = KeyFactory.getInstance("RSA").generatePublic(spec)
                return KeyPair(publicKey, privateKey)
            }
            else -> {
                throw IOException("Invalid PEM file")
            }

        }
    }
}