Java Crypto Extensions Read DER Encoded Asymmetric Keys

In a work project that heavily focused on asymmetric crypto, certificates, and digital signatures, we had to switch from PEM-formatted keys and certificates to DER-encoded data. Many of the examples I found on the internet always focused on reading PEM data with Bouncy Castle. I wanted to determine how much you can do without an additional library.

Spoiler: Not everything. But, let’s say, the stuff you likely care about.

A Story About OpenSSL & Formats

The starting point of this is a key pair, and you are likely to create one with OpenSSL. Its default output is PEM, so we start from there. You can also instruct OpenSSL to write DER when you generate the key by passing the command line argument -outform DER (or lowercase, it does not matter). This option is also used to convert from PEM to DER.

RSA

Let us start with RSA keys, which are still the most prevalent. Afterward, I will show you how to handle Elliptic Curve keys.

openssl genpkey -algorithm RSA -out genpkey_rsa_private_key.pem -pkeyopt rsa_keygen_bits:2048

You can also use the following command. However, according to a comment on StackExchange, genpkey is the recommended way to go.

openssl genrsa -out genrsa_private_key.pem 2048

Depending on your OpenSSL version, there may be differences though. I could not narrow down the exact version, so you must look at the generated PEM. I am using OpenSSL 3.2.1. If the PEM starts with -----BEGIN PRIVATE KEY-----, you are golden. If it is -----BEGIN RSA PRIVATE KEY-----, a conversion is necessary. That is because key information can be encoded in different ways. Java requires PKCS8, which is represented by the first one. From what I understood, the second one is PKCS1.

(Much data formats. Many confusing.)

Read More »