PrivateKeyGenerated by OpenSSL to RSACRTPrivateKey object

305 views Asked by At

there is a privateKey file in PEM format generated by following Openssl command to generate a .csr.

openssl req -newkey rsa:2048 -nodes -out %~dp0\req.csr -keyout %~dp0\..\private.key -sha256 -config %~dp0\..\cfg.cfg

Now, id like to get a chinese remainder theorem - key object out of that file. But i am not successfull unitl now. So maybe you can give me a helping hand.

1

There are 1 answers

0
dave_thompson_085 On BEST ANSWER

I'm not sure if you want a BC-only (LWAPI?) solution, or if you'll take JCE which can use either Sun or BC provider. If the latter:

RSA keypairs generated and written by openssl are always in CRT form unless you work hard to prevent it, and req doesn't. For openssl 1.0.0+ the privatekey file from req -newkey (and most other things) is PKCS#8 containing PKCS#1 CRT; in older versions it is "legacy" PKCS#1 CRT and must be reformatted into PKCS#8, most easily by (edit) openssl pkcs8 -topk8 -nocrypt -in *file* -out *file* [-outform der] (see next). PKCS#8 can be and often is encrypted, but req -newkey -nodes is unencrypted, and so is pkcs8 -nocrypt.

JCE can read (edit) unencrypted DER PKCS#8 containing PKCS#1 CRT (among other things). It's easier to convert PEM to DER with openssl since it's a simple commandline (especially if combined with legacy to PKCS#8 conversion, see above); then in Java:

  • read the (edit) unencrypted PKCS#8 DER into a byte[] let's say buffer and
  • pass that to java.security.KeyFactory.getInstance("RSA"[,provider]) .generatePrivate(buffer) (or equivalent).

The result has provider-dependent type but in either case it implements interface java.security.interfaces.RSAPrivateCrtKey.

JCE doesn't do PEM itself. If you have PEM, read it, strip the BEGIN/END lines, convert remaining base64 to bytes, then proceed with JCE.