检查 base64 文本是否是有效的 RSA public 密钥 (4096)

Check if a base64 text is a valid RSA public key (4096)

我如何检查 base64 文本是否是有效的 RSA public 密钥格式(在 java 中)。

==> 检查是 base64

==> 检查是否为有效的 RSA 4096 位密钥。

谢谢

这样的东西应该适合你,注意我添加的代码中的注释

我参考了这个答案并对代码做了一些修改: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;
}