Search code examples
javarsajava-17

How to create Java Key object from RSA public key in PEM format Java17


I am upgrading from Java 8 to Java 17. I had working code to convert RSA public key to a Java Key object using classes in sun.security.util. This is no longer allowed (as of Java 9 I believe). How can I update my code to be compatible with Java 17? I would prefer to use Bouncycastle, as it is already a dependency in my project.

My previous code:

            String keyData = r.getPublicKey()
                    .replace("-----BEGIN RSA PUBLIC KEY-----", "")
                    .replace("-----END RSA PUBLIC KEY-----", "");
            byte[] content = Base64.decodeBase64(keyData);
            DerInputStream derReader = new DerInputStream(content);
            DerValue[] seq = derReader.getSequence(0);
            BigInteger modulus = seq[0].getBigInteger();
            BigInteger publicExp = seq[1].getBigInteger();
            KeyFactory kf = KeyFactory.getInstance("RSA");
            RSAPublicKeySpec keySpec = new RSAPublicKeySpec(modulus, publicExp);
            PublicKey pk = kf.generatePublic(keySpec);

The following classes were pulled from sun.security.util:

sun.security.util.DerInputStream;
sun.security.util.DerValue;

Solution

  • Based on @david_thompson_085's comment and this post, I got the following solution to work.

    PEMParser pemParser = new PEMParser(new StringReader(r.getPublicKey()));
    JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
    Object o = pemParser.readObject();
    PublicKey pk = converter.getPublicKey((SubjectPublicKeyInfo)o);
    

    Note, as described in the referenced post, I did have to set BouncyCastle as my security provider.

    Security.addProvider(new BouncyCastleProvider());