Search code examples
javasslssl-certificatejssemutual-authentication

SSL socket server get certificate cn after handshake


I have an SSL socket server running with a 2-side handshake required (for which I'm using self signed certificates). After the handshake was successful, I would like to check the client certificate's cn on the server side. Unfortunately this field is set to Unknown.

Here is the code I used to determine the cn field value:

((SSLSocket) socket).addHandshakeCompletedListener(new HandshakeCompletedListener() {
    @Override
    public void handshakeCompleted(HandshakeCompletedEvent hce) {
        X509Certificate cert = (X509Certificate)hce.getLocalCertificates()[0];
        String certName = cert.getSubjectX500Principal().getName().substring(3,cert.getSubjectX500Principal().getName().indexOf(","));
        System.out.println(certName);
    }
});

Which prints Unknown

Aditionally, I checked the client's keyStore using this command:

keytool -list -v -keystore clientStore.jks

Which prints

Keystore-type: JKS
Keystore-provider: SUN

Keystore contains 1 entry

Aliasname: test
creation date: 23.04.2018
entry type: PrivateKeyEntry
certificate length: 1
certificate[1]:
owner: CN=test, OU="Org Unit", O=Org, L=City, ST=State, C=DE
...

As you can see, the client store's certificate's cn is set. However it is inexplicable to me why it then seems not to be transmitted to the server.

I would be glad for every kind of help.

Best regards,

Galveston01


Solution

  • After the handshake was successful, I would like to check the client certificate's cn on the server side.

    To check what certificates you have received you need to call getPeerCertificates instead of getLocalCertificates, which is for the certificates you sent.

    And you should read carefully the doc :

    public X500Principal getSubjectX500Principal()

    Returns the subject (subject distinguished name) value from the certificate as an X500Principal. If the subject value is empty, then the getName() method of the returned X500Principal object returns an empty string ("").

    For this reason it's not recommended to call indexOf() substring() without checking first the input.