How do I check if an X509 certificate has been revoked in Java?

前端 未结 2 409
离开以前
离开以前 2020-12-29 14:21

I have googled around all over the place for this, and asked in other communities, and I keep getting forwarded to the oracle document that discusses the spec. However, that

2条回答
  •  醉梦人生
    2020-12-29 14:56

    Every CA publishes the list of the certificates it has revoked. This list includes the serial number of the certificates and the revocation date

    to get the url of the certificate revocation list (CRL) follow the below steps

    • open the certificate
    • go to Details Tab and find the field "CRL Distribution Point" in the details list

    It will show you the value something like this

    [1]CRL Distribution Point Distribution Point Name: Full Name: URL=mscrl.microsoft.com/pki/mscorp/crl/msitwww2.crl URL=crl.microsoft.com/pki/mscorp/crl/msitwww2.crl

    So in your code you need to download these files and check for the certificate serial number in them to see if it's revoked or not

    Find below the sample code for it

    public class CertVerification {
    
    
        public static void main(String[] args) throws Exception {
    
            String certificatePath = "C:\\Users\\user1\\Desktop\\test.cer";
    
            CertificateFactory cf = CertificateFactory.getInstance("X509");
    
            X509Certificate certificate = null;
            X509CRLEntry revokedCertificate = null;
            X509CRL crl = null;
    
            certificate = (X509Certificate) cf.generateCertificate(new FileInputStream(new File(certificatePath)));
    
            URL url = new URL("http://.crl");
            URLConnection connection = url.openConnection();
    
            try(DataInputStream inStream = new DataInputStream(connection.getInputStream())){
    
                crl = (X509CRL)cf.generateCRL(inStream);
            }
    
            revokedCertificate = crl.getRevokedCertificate(certificate.getSerialNumber());
    
            if(revokedCertificate !=null){
                System.out.println("Revoked");
            }
            else{
                System.out.println("Valid");
            }
    
        }
    
    
    }
    

    Please See

    These lists are updated periodically

    You can get these Revocation URL's from the certificate as well, i have just given an example

    This is just a basic example to give you a head start

    Update

    I found this sample class to check certificate, it also verifies with the CRL issued by the certificate's CA and certification chain, so you don't need to provide the CRL url as well

    https://svn.cesecore.eu/svn/ejbca/branches/Branch_3_2_3_utf8/ejbca/doc/samples/ValidateCertUseCRL.java

提交回复
热议问题