I want to generate a private key in the java standard for the PrivateKey format using RSA, but always in the invalid format. I have already tried several keys with openssl, generating by java and I can not find a solution. Follow the code to create a PrivateKey.
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(readContent("/home/renato/Downloads/mestrado/certificados/private.pem"));
KeyFactory factory = KeyFactory.getInstance("RSA");
PrivateKey privKey = factory.generatePrivate(spec);
Code to generate the keys
public static void main (String[] args) throws Exception {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair kp = kpg.generateKeyPair();
System.out.println ("-----BEGIN PRIVATE KEY-----");
System.out.println (Base64.getMimeEncoder().encodeToString( kp.getPrivate().getEncoded()));
System.out.println ("-----END PRIVATE KEY-----");
System.out.println ("-----BEGIN PUBLIC KEY-----");
System.out.println (Base64.getMimeEncoder().encodeToString( kp.getPublic().getEncoded()));
System.out.println ("-----END PUBLIC KEY-----");
}
Error that happens
java.security.InvalidKeyException: invalid key format