Search code examples
javasslcertificatex509certificate

How to fix empty getPublicKey in X509Certificate


I created a java method which equals X509Certificate#certificate.getPublicKey().getAlgorithm()
with my String. But I have bug when I invoke getPublicKey() it is null and I have ArrayIndexOutOfBoundsException. How to fix this. Condition (getPublicKey != null) does not work for me.

    public boolean supports(X509Certificate certificate) {
            try {
                final String algorithm = certificate.getPublicKey().getAlgorithm();
                if ("RSA".equals(algorithm)) {
                    return certificate.getSignature().length * 8 == keySize;
                }
            } catch (ArrayIndexOutOfBoundsException ex) {
                log.warn(" can't get the public key from certificate ", ex);
            }
        return false;
    }
}

Maybe use some condition?

I want my app not to crash.


Solution

  • I fixed it using this condition

    boolean[] withKeys = certificate.getKeyUsage();
    if (withKeys != null && withKeys[5]) 
    

    You can also check your public key for availability

    java.security.cert.X509Certificate#getKeyUsage()