com.archivas.clienttools.arcutils.utils.net.SSLCertChain.java Source code

Java tutorial

Introduction

Here is the source code for com.archivas.clienttools.arcutils.utils.net.SSLCertChain.java

Source

// Copyright 2007 Hitachi Data Systems
// All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.

package com.archivas.clienttools.arcutils.utils.net;

import java.io.Serializable;
import java.math.BigInteger;
import java.security.Principal;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.commons.codec.digest.DigestUtils;

public class SSLCertChain implements Serializable {

    private static final Logger LOG = Logger.getLogger(SSLCertChain.class.getName());

    private String authType = null;
    private List<X509Certificate> certificateList = null;
    private Exception certificateException = null;

    public SSLCertChain() {
    }

    public SSLCertChain(final String authType, final ArrayList<X509Certificate> certificateList) {
        this.authType = authType;
        this.certificateList = certificateList;
    }

    public SSLCertChain(final String authType, final X509Certificate[] certificates) {
        this.authType = authType;
        setCertificateList(certificates);
    }

    public SSLCertChain(final String authType, final X509Certificate[] certificates,
            Exception certificateException) {
        this.authType = authType;
        this.certificateException = certificateException;
        setCertificateList(certificates);
    }

    public String getAuthType() {
        return authType;
    }

    public void setAuthType(final String authType) {
        this.authType = authType;
    }

    public List<X509Certificate> getCertificateList() {
        return certificateList;
    }

    public void setCertificateList(final List<X509Certificate> certificateList) {
        this.certificateList = certificateList;
    }

    public void setCertificateList(final X509Certificate[] certificates) {
        this.certificateList = Arrays.asList(certificates);
    }

    public Exception getCertificateException() {
        return certificateException;
    }

    public void setCertificateException(final Exception certificateException) {
        this.certificateException = certificateException;
    }

    public String toDetailString() {
        final StringBuilder sb = new StringBuilder();
        sb.append("SSLCertChain");
        sb.append("{authType='").append(authType).append('\'');
        sb.append(", certificateList=").append(certificateList);
        sb.append('}');
        return sb.toString();
    }

    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append("SSLCertChain");
        sb.append("{authType='").append(authType).append('\'');
        sb.append(", issuedToCN='").append(getIssuedToCommonName()).append('\'');
        sb.append(", IssuedByCN='").append(getIssuedByCommonName()).append('\'');
        sb.append(", validRangeString='").append(getValidRangeString()).append('\'');
        sb.append('}');
        return sb.toString();
    }

    public Map<String, String> getDNInfo(Principal principal) {
        Map<String, String> map = new LinkedHashMap<String, String>();
        StringTokenizer st = new StringTokenizer(principal.getName(), ",");
        while (st.hasMoreTokens()) {
            String token = st.nextToken().trim();
            int index = token.indexOf('=');
            if (index > -1) {
                String key = token.substring(0, index).trim();
                String val = token.substring(index + 1).trim();
                map.put(key, val);
            } else {
                LOG.log(Level.WARNING, "Unexpected string parsing error looking for '=' in " + principal.getName());
            }
        }
        return map;
    }

    public Map<String, String> getIssuedToDNInfo() {
        X509Certificate cert = getCertificateList().get(0);
        return getDNInfo(cert.getSubjectX500Principal());
    }

    public String getIssuedToCommonName() {
        return getIssuedToDNInfo().get("CN");
    }

    public String getIssuedToOrganization() {
        return getIssuedToDNInfo().get("O");
    }

    public String getIssuedToOrgUnit() {
        return getIssuedToDNInfo().get("OU");
    }

    public String getIssuedToLocation() {
        return getIssuedToDNInfo().get("L");
    }

    public String getIssuedToState() {
        return getIssuedToDNInfo().get("ST");
    }

    public String getIssuedToCountry() {
        return getIssuedToDNInfo().get("C");
    }

    public Map<String, String> getIssuedByDNInfo() {
        X509Certificate cert = getCertificateList().get(0);
        return getDNInfo(cert.getIssuerX500Principal());
    }

    public String getIssuedByCommonName() {
        return getIssuedByDNInfo().get("CN");
    }

    public String getIssuedByOrganization() {
        return getIssuedByDNInfo().get("O");
    }

    public String getIssuedByOrgUnit() {
        return getIssuedByDNInfo().get("OU");
    }

    public String getIssuedByLocation() {
        return getIssuedByDNInfo().get("L");
    }

    public String getIssuedByState() {
        return getIssuedByDNInfo().get("ST");
    }

    public String getIssuedByCountry() {
        return getIssuedByDNInfo().get("C");
    }

    public BigInteger getSerialNumber() {
        X509Certificate cert = getCertificateList().get(0);
        return cert.getSerialNumber();
    }

    public String getSerialNumberString() {
        X509Certificate cert = getCertificateList().get(0);
        BigInteger sn = cert.getSerialNumber();
        return byteArrayToColonSeparatedHexString(sn.toByteArray(), ":");
    }

    /**
     * Convert a byte[] array to readable string format.
     * 
     * @return result String buffer in String format
     * @param in
     *            byte[] buffer to convert to string format
     */
    public static String byteArrayToHexString(byte in[]) {
        return byteArrayToColonSeparatedHexString(in, null);
    }

    /**
     * Convert a byte[] array to readable string format.
     * 
     * @return result String buffer in String format
     * @param in
     *            byte[] buffer to convert to string format
     */
    public static String byteArrayToColonSeparatedHexString(byte in[], String separatorStr) {
        byte ch = 0x00;
        int i = 0;
        if (in == null || in.length <= 0) {
            return null;
        }

        String pseudo[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F" };

        StringBuffer out = new StringBuffer(in.length * 2);

        while (i < in.length) {
            ch = (byte) (in[i] & 0xF0); // Strip off high nibble
            ch = (byte) (ch >>> 4); // shift the bits down
            ch = (byte) (ch & 0x0F); // must do this is high order bit is on!
            out.append(pseudo[(int) ch]); // convert thenibble to a String Character
            ch = (byte) (in[i] & 0x0F); // Strip off low nibble
            out.append(pseudo[(int) ch]); // convert the nibble to a String Character
            i++;

            if (separatorStr != null && i < in.length) {
                out.append(separatorStr);
            }
        }
        String rslt = new String(out);
        return rslt;
    }

    public Date getValidNotBefore() {
        X509Certificate cert = getCertificateList().get(0);
        return cert.getNotBefore();
    }

    public Date getValidNotAfter() {
        X509Certificate cert = getCertificateList().get(0);
        return cert.getNotAfter();
    }

    public String getValidNotBeforeString() {
        return "" + getValidNotBefore();
    }

    public String getValidNotAfterString() {
        return "" + getValidNotAfter();
    }

    public String getValidRangeString() {
        Date notBefore = getValidNotBefore();
        Date notAfter = getValidNotAfter();
        SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");

        return format.format(notBefore) + " to " + format.format(notAfter);
    }

    public String getFingerprint() {
        X509Certificate cert = getCertificateList().get(0);
        return new String(cert.getSignature());
    }

    public String getSignatureAlgorithm() {
        X509Certificate cert = getCertificateList().get(0);
        return cert.getSigAlgName();
    }

    public String getSignatureString() {
        X509Certificate cert = getCertificateList().get(0);
        return byteArrayToColonSeparatedHexString(cert.getSignature(), ":");
    }

    public String getPublicKeyAlgorithm() {
        X509Certificate cert = getCertificateList().get(0);
        return cert.getPublicKey().getAlgorithm();
    }

    public String getPublicKeyString() {
        X509Certificate cert = getCertificateList().get(0);
        return byteArrayToColonSeparatedHexString(cert.getPublicKey().getEncoded(), ":");
    }

    public String getMD5FingerprintString() {
        X509Certificate cert = getCertificateList().get(0);
        String s = null;
        try {
            s = byteArrayToColonSeparatedHexString(DigestUtils.md5(cert.getTBSCertificate()), ":");
        } catch (CertificateEncodingException e) {
            LOG.log(Level.WARNING, "Error generating MD5 Fingerprint for SSL Certificate : " + toString());
        }
        return s;
    }

    public String getShaFingerprintString() {
        X509Certificate cert = getCertificateList().get(0);
        String s = null;
        try {
            s = byteArrayToColonSeparatedHexString(DigestUtils.sha(cert.getTBSCertificate()), ":");
        } catch (CertificateEncodingException e) {
            LOG.log(Level.WARNING, "Error generating MD5 Fingerprint for SSL Certificate : " + toString());
        }
        return s;
    }

    public String getValidity() {
        String validity = "The cert is valid";
        try {
            X509Certificate cert = getCertificateList().get(0);
            cert.checkValidity();
        } catch (CertificateExpiredException e) {
            LOG.log(Level.WARNING, "Unexpected Exception", e);
            validity = e.toString();

        } catch (CertificateNotYetValidException e) {
            LOG.log(Level.WARNING, "Unexpected Exception", e);
            validity = e.toString();

        }
        return validity;
    }
}