Skip to content

Instantly share code, notes, and snippets.

@chiuki
Created May 2, 2017 15:50
Show Gist options
  • Save chiuki/fd581a52ecc51fb9ed7e447d083f92cc to your computer and use it in GitHub Desktop.
Save chiuki/fd581a52ecc51fb9ed7e447d083f92cc to your computer and use it in GitHub Desktop.
Check the CN of a certificate from a server. The certificate can be self-signed, and the server does not have to be HTTP.
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
/**
* Run with
* javac CheckCN.java && java CheckCN
*/
public class CheckCN {
public static void main(String[] args) {
boolean matched = verifyCN("android.com", 443, "CN=*.google.com");
System.out.println("CN found? " + matched);
}
private static boolean verifyCN(String host, int port, String expectedSubstring) {
CertMatchingTrustManager trustManager
= new CertMatchingTrustManager(expectedSubstring);
SocketFactory factory = newSslSocketFactory(trustManager);
try {
SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
socket.startHandshake();
} catch (IOException e) {
}
return trustManager.isMatching();
}
private static SSLSocketFactory newSslSocketFactory(TrustManager trustManager) {
try {
TrustManager[] trustManagers = new TrustManager[] {
trustManager
};
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagers, null);
return sslContext.getSocketFactory();
} catch (KeyManagementException | NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
private static class CertMatchingTrustManager implements X509TrustManager {
private final String expectedSubstring;
private boolean matching = false;
public CertMatchingTrustManager(String expectedSubstring) {
this.expectedSubstring = expectedSubstring;
}
public boolean isMatching() {
return matching;
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
for (X509Certificate certificate : chain) {
String toMatch = certificate.getSubjectDN().getName();
System.err.println(toMatch);
if (toMatch.contains(expectedSubstring)) {
matching = true;
return;
}
}
throw new CertificateException("Substring not found");
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment