Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create RSAPrivateKey from PEM encoded string

SO I have this code

private static RSAPrivateKey buildRSAPrivateKey(String privateKey) {
        PEMReader pemReader = new PEMReader(new StringReader(privateKey));
        try {
            KeyPair pair = (KeyPair) pemReader.readObject();
            RSAPrivateKey result = (RSAPrivateKey)pair.getPrivate();
            pemReader.close();
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

It works fine using bouncycastle, however I need this to function on Android, so I imported SpongyCastle, however spongy castle does not have PEMReader (apparently PEMReader is in an older bouncycastle version)

How can I create an RSAPrivateKey equivalent to the above code without using bouncycastle's PEMReader?

like image 981
fernandohur Avatar asked Nov 11 '22 07:11

fernandohur


1 Answers

I hope, at least this answer will help others. Because bouncy castle is totally deprecated its support for android P.

Security.insertProviderAt(new org.spongycastle.jce.provider.BouncyCastleProvider(), 1);
StringReader reader = new StringReader(privateKeySerialized); /*privateKeySerialized -> RSA key*/
PublicKey pKey = null;
try {
  PemReader pemReader = new PemReader(reader);
  PEMParser pemParser = new PEMParser(pemReader);
  PEMKeyPair keyPair = (PEMKeyPair) pemParser.readObject();
  JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
  pKey = converter.getPublicKey(keyPair.getPublicKeyInfo());
  pemReader.close();
} catch (IOException i) {
  i.printStackTrace();
}
like image 86
Balaje Venkat Avatar answered Nov 15 '22 06:11

Balaje Venkat