Problem

  • I needed to load a private key into the Java keystore at runtime to use for mutual TLS
  • I had an RSA Private Key in PKCS#1
  • It’s easier to work with PKCS#8 format keys when loading them into Java applications

Solution

  • Convert the original PKCS#1 format key into a PKCS#8 format ready to load

Worked Example

  • I had an existing key but for this example we’ll generate a new example key:
    openssl genrsa -f4 -out rsa.key 2048
    
  • This generates a key in PKCS#1 format like:
    -----BEGIN RSA PRIVATE KEY-----
    MIIEogIBAAKCAQEArKnetE3gAf7srZfKZoZGgfHnayCUDmgzYSRYN4LhsNdv01LS
    ehWaQON/QmysBHQ/DVBlXJV4tQm1tDvdgUSrtQ4MHr3V2T0du/cbd1boO4O/0bcw
    ...... omitted for brevity ......
    -----END RSA PRIVATE KEY-----
    
  • Convert the rsa.key to PKCS#8 format using:
    openssl pkcs8 -topk8 -inform PEM -outform DER -nocrypt -in rsa.key -out rsa.key.der
    
  • rsa.key.der generated is in binary format so isn’t easily viewable
  • You can confirm that the conversion completed successfully by viewing it:
    openssl rsa -in rsa.key.der -inform DER
    
  • This prints out:
    -----BEGIN RSA PRIVATE KEY-----
    MIIEogIBAAKCAQEArKnetE3gAf7srZfKZoZGgfHnayCUDmgzYSRYN4LhsNdv01LS
    ehWaQON/QmysBHQ/DVBlXJV4tQm1tDvdgUSrtQ4MHr3V2T0du/cbd1boO4O/0bcw
    ...... omitted for brevity ......
    -----END RSA PRIVATE KEY-----
    
  • This should match the contents of the original rsa.key
  • We can now use this and load it into the Java keystore at runtime for our needs