1- Generating a Private Key, from the command line:

openssl genrsa -aes256 -out private.key 2048

  1. 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);

0 Answers