Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.security.cert.Certificate;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;

public class Main {
    /**
     * Returns the X509Certificate for the server this session is connected to. The certificate may be null.
     *
     * @param sslSession SSL session connected to upstream server
     * @return the X.509 certificate from the upstream server, or null if no certificate is available
     */
    public static X509Certificate getServerCertificate(SSLSession sslSession) {
        Certificate[] peerCertificates;
        try {
            peerCertificates = sslSession.getPeerCertificates();
        } catch (SSLPeerUnverifiedException e) {
            peerCertificates = null;
        }

        if (peerCertificates != null && peerCertificates.length > 0) {
            Certificate peerCertificate = peerCertificates[0];
            if (peerCertificate != null && peerCertificate instanceof X509Certificate) {
                return (X509Certificate) peerCertificates[0];
            }
        }

        // no X.509 certificate was found for this server
        return null;
    }
}