ENGLISH

JAVA RSA Error - invalid key format

개미v 2021. 1. 24. 15:11

This error occurred when I was trying to use RSA private key and public key in Java.

 

■ Error

Exception in thread "main" java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format

at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:252)

at java.security.KeyFactory.generatePrivate(KeyFactory.java:372)

at Main.main(Main.java:43)

Caused by: java.security.InvalidKeyException: invalid key format

at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:331)

at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:356)

at sun.security.rsa.RSAPrivateCrtKeyImpl.<init>(RSAPrivateCrtKeyImpl.java:130)

at sun.security.rsa.RSAPrivateCrtKeyImpl.newKey(RSAPrivateCrtKeyImpl.java:80)

at sun.security.rsa.RSAKeyFactory.generatePrivate(RSAKeyFactory.java:357)

at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:248)

... 2 more

■ Cauese

RSA PEM file format supported by Java does not match
Java does not support PKCS#1, only PKCS#8

 

- PEM file PKCS#1 looks like this.

-----BEGIN RSA PRIVATE KEY-----

.

.

.

-----END RSA PRIVATE KEY-----

- PEM file PKCS#8 looks like this.

-----BEGIN PUBLIC KEY-----

.

.

.

-----END PUBLIC KEY-----

■ Solution

- Use openssl to convert RSA private keys from PKCS#1 to PKCS#8 for use in Java

# 개인키 pkcs#8 형식으로 변환
pkcs8 -in private_key1.pem -inform PEM -out private_key8.pem -outform PEM -topk8 -nocrypt

 

- If JAVA generated a private key, it is PKCS#8 by default.
The format is correct, so you need to find another cause.