17

Is it possible to read the RSA private key of format PKCS1 in JAVA without converting to PKCS8? if yes, sample code is appreciated.

-----BEGIN RSA PRIVATE KEY-----
 BASE64 ENCODED DATA
-----END RSA PRIVATE KEY-----
Jenananthan
  • 1,381
  • 2
  • 10
  • 20

1 Answers1

30

Java does not come with out-of-the-box support for PKCS1 keys. You can however use Bouncycastle

PEMParser pemParser = new PEMParser(new FileReader(privateKeyFile));
JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
Object object = pemParser.readObject();
KeyPair kp = converter.getKeyPair((PEMKeyPair) object);
PrivateKey privateKey = kp.getPrivate();
Pieter De Clercq
  • 1,951
  • 1
  • 17
  • 29
pedrofb
  • 37,271
  • 5
  • 94
  • 142
  • 2
    I got an error: `java.security.NoSuchProviderException: no such provider: BC` – Alex Pavlov Dec 05 '18 at 15:54
  • 8
    I solved it by adding `Security.addProvider(new BouncyCastleProvider());` – Alex Pavlov Dec 05 '18 at 16:22
  • @pedrofb .... I am trying this in android I cannot resolve `PEMParser` and `JcaPEMKeyConverter` .... I tried using `https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk15on/1.55` ... but didn't work .... Which Jar I need to use or which grade do I need to use for this ? – Devrath Jan 25 '19 at 07:47
  • 3
    You will need `bcpkix` and `bcprov`. Try with `compile "org.bouncycastle:bcprov-jdk15on:$bouncycastleVersion" compile "org.bouncycastle:bcpkix-jdk15on:$bouncycastleVersion"` – pedrofb Jan 25 '19 at 07:56
  • 2
    Here is a solution without Bouncycastle: https://stackoverflow.com/a/55339208/975386 – Jean-Alexis Aufauvre Mar 25 '19 at 13:46
  • With most Java (at least Oracle and OpenJDK) technically you don't need to `set` or have configured the BC provider; JcaPEMKeyConverter works fine with the default provider(s). But you do need the bcprov _jar_ because BC's asn1 classes are in it, and given you have the jar you might as well use the provider classes. – dave_thompson_085 Aug 29 '22 at 01:21