8

I want to verify the X509 certificate presented by a client against a CRL to see if it has been revoked. I have successfully instanciated a java.security.cert.X509CRL, but I am having problems retrieving the certificate of the session:

try {
    SSLSocket s = (SSLSocket) serverSocket.accept();
    s.setSoTimeout(TIMEOUT_RW * 1000);
    s.startHandshake();
    SSLSession session = s.getSession();
    X509Certificate[] cert = session.getPeerCertificateChain();
    if (crl.isRevoked(cert[0])) {
        System.err.println("Attempted to stablish connection using revoked certificate");
    } else {
        ...
    }
} catch (Exception ex) {
    System.err.println("Something went wrong");
}

SSLSession belongs to the javax.net.ssl package, and its method getPeerCertificateChain() returns a javax.security.cert.X509Certificate[], which cannot be converted to the java.security.cert.X509Certificate[] that I need to feed the java.security.cert.X509CRL. How can it be done?

user2891462
  • 3,033
  • 2
  • 32
  • 60

1 Answers1

12

javax.security.cert.X509Certificate is deprecated. Get java.security.cert.Certificate[] by session.getPeerCertificates();, and then pass it to your crl.isRevoked implementation.

See also:

The classes in the package javax.security.cert exist for compatibility with earlier versions of the Java Secure Sockets Extension (JSSE). New applications should instead use the standard Java SE certificate classes located in java.security.cert.

You can convert java.security.cert.Certificate to java.security.cert.X509Certificate (source):

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    ByteArrayInputStream bais = new ByteArrayInputStream(certificate.getEncoded());
    X509Certificate x509 =  (X509Certificate) cf.generateCertificate(bais);
user2891462
  • 3,033
  • 2
  • 32
  • 60
MGorgon
  • 2,547
  • 23
  • 41
  • The problem with that option (I contemplated it) is that later I need to use methods of X509Certificate, so it was not good enough for me. – user2891462 Jul 06 '14 at 22:29
  • But `Certificate` is abstract class - i bet that `cert[0]` is `instanceof` `X509Certificate` class. Just check it and cast – MGorgon Jul 06 '14 at 22:31
  • @user2891462 If not, you can perform conversion like this implemented `X509Certificate[] convertCertificates(Certificate[] certsIn)` method: https://groups.google.com/forum/#!topic/android-developers/HCiHwBKOsrI – MGorgon Jul 06 '14 at 22:35