1- Generating a Private Key, from the command line:
openssl genrsa -aes256 -out private.key 2048
from
java
, read it:String privateKey = IOUtils.toString(TestJwtSecurityUtil.class.getResourceAsStream("/private.key")); privateKey = privateKey.replace("-----BEGIN RSA PRIVATE KEY-----", ""); privateKey = privateKey.replace("-----END RSA PRIVATE KEY-----", ""); privateKey = privateKey.replaceAll("\\s+",""); byte[] encodedKey = DatatypeConverter.parseBase64Binary( privateKey ); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encodedKey); KeyFactory kf = KeyFactory.getInstance("RSA"); PrivateKey pKey = kf.generatePrivate(keySpec); // fails
Got exception:
Exception in thread "main" java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : DerInputStream.getLength(): lengthTag=58, too big.
I tried to convert to base64:
byte[] encodedKey = DatatypeConverter.parseBase64Binary( encodedString );
PrivateKey pKey = kf.generatePrivate(keySpec); // fails
got:
Exception in thread "main" java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format
at java.base/sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:251)
Q: how to pass this? To make private key being read so in the end I could sing the JWT token:
final JwtBuilder builder = Jwts.builder().setId("id1")
....
.signWith(signatureAlgorithm, pKey);
openssl pkcs8 -topk8 -nocrypt
, oropenssl pkey
. Or generate withkeytool
or JCE in the first place instead of OpenSSL. @michalk: no,genrsa
does not encrypt, but it uses 'traditional' (PKCS1) format not PKCS8 format. – dave_thompson_085 Jun 2 '19 at 6:58-aes256
does not encrypt the key content while usinggenrsa
? – michalk Jun 2 '19 at 7:05