2

How can i check if a base64 text is a valid RSA public key format (in java).

==> check that is in base64

==> check that is valid key of RSA 4096 bits.

Thank you

Singa
  • 351
  • 2
  • 11

1 Answers1

3

Something like this should work for you, pay attention to the comments in the code that I added

I referred to this answer and made few modifications to the code: How can I construct a java.security.PublicKey object from a base64 encoded string?

public static PublicKey getKey(String key){
    try{
        //if base64 is invalid, you will see an error here
        byte[] byteKey = Base64.getDecoder().decode(key);
        //if it is not in RSA public key format, you will see error here as java.security.spec.InvalidKeySpecException
        X509EncodedKeySpec X509publicKey = new X509EncodedKeySpec(byteKey);
        KeyFactory kf = KeyFactory.getInstance("RSA");

        return kf.generatePublic(X509publicKey);
    }
    catch(Exception e){
        e.printStackTrace();
    }

    return null;
}
Chandan
  • 640
  • 4
  • 10