package org.xbib.net.security.test;

import org.junit.jupiter.api.Test;
import org.xbib.net.security.ssl.util.CertificateUtils;

import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.logging.Logger;

public class SecureSocketReaderTest {

    private static final Logger logger = Logger.getLogger(SecureSocketReaderTest.class.getName());

    public SecureSocketReaderTest() {
    }

    @Test
    public void dumpServerCertificateChainAsPem() throws Exception {
        SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
        try (SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket("xbib.org", 443)) {
            sslsocket.startHandshake();
            SSLSession sslSession = sslsocket.getSession();
            Certificate[] certificates = sslSession.getPeerCertificates();
            for (Certificate certificate : certificates) {
                X509Certificate x509Certificate = (X509Certificate) certificate;
                logger.info("not before = " + x509Certificate.getNotBefore());
                logger.info("not after = " + x509Certificate.getNotAfter());
                logger.info(CertificateUtils.convertToPem(certificate));
            }
        }
    }
}
