Java
Chilkat2 Java
Get the Server Certificate from a TLS Connection
See more Socket/SSL/TLS Examples
Demonstrates Socket.GetServerCert, which copies the certificate presented by the remote TLS server into a Cert object for inspection.
Background. The method returns false when the socket is not connected, is not using TLS, or no server certificate is available. Inspecting the certificate lets an application validate the server's identity.
Chilkat Java Downloads
import com.chilkatsoft.chilkat2.Cert;
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Socket;
public class ChilkatExample {
public static void main(String[] args) {
Socket socket = new Socket();
// Connect to the server using TLS.
boolean bTls = true;
int maxWaitMs = 5000;
try {
socket.connect("example.com", 5000, bTls, maxWaitMs);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
// Copy the certificate presented by the remote TLS server, then inspect it. This can be used to
// validate the server's identity.
Cert cert = new Cert();
try {
socket.getServerCert(cert);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
System.out.println("Server certificate subject: " + cert.getSubjectCN());
System.out.println("Issued by: " + cert.getIssuerCN());
}
}