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.
'ENGLISH' 카테고리의 다른 글
JAVA object to byte array conversion method (0) | 2021.01.30 |
---|---|
How to Auto-print an Infinite Ink Printer (0) | 2018.12.02 |
Infinite Ink Printer InkPad (0) | 2018.12.02 |
Tomcat Error - java.util.concurrent.ExecutionException:org.apache.catalina.LifeException (0) | 2018.12.02 |
Example of adding an Android app Adfit ad (0) | 2018.12.02 |