mitm.common.hibernate.X509CertificateUserType.java Source code

Java tutorial

Introduction

Here is the source code for mitm.common.hibernate.X509CertificateUserType.java

Source

/*
 * Copyright (c) 2008-2011, Martijn Brinkers, Djigzo.
 * 
 * This file is part of Djigzo email encryption.
 *
 * Djigzo is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License 
 * version 3, 19 November 2007 as published by the Free Software 
 * Foundation.
 *
 * Djigzo is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public 
 * License along with Djigzo. If not, see <http://www.gnu.org/licenses/>
 *
 * Additional permission under GNU AGPL version 3 section 7
 * 
 * If you modify this Program, or any covered work, by linking or 
 * combining it with aspectjrt.jar, aspectjweaver.jar, tyrex-1.0.3.jar, 
 * freemarker.jar, dom4j.jar, mx4j-jmx.jar, mx4j-tools.jar, 
 * spice-classman-1.0.jar, spice-loggerstore-0.5.jar, spice-salt-0.8.jar, 
 * spice-xmlpolicy-1.0.jar, saaj-api-1.3.jar, saaj-impl-1.3.jar, 
 * wsdl4j-1.6.1.jar (or modified versions of these libraries), 
 * containing parts covered by the terms of Eclipse Public License, 
 * tyrex license, freemarker license, dom4j license, mx4j license,
 * Spice Software License, Common Development and Distribution License
 * (CDDL), Common Public License (CPL) the licensors of this Program grant 
 * you additional permission to convey the resulting work.
 */
package mitm.common.hibernate;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.CertificateParsingException;
import java.security.cert.X509Certificate;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

import mitm.common.security.SecurityConstants;
import mitm.common.security.SecurityFactoryFactory;
import mitm.common.security.certificate.X509CertificateInspector;
import mitm.common.util.HexUtils;

import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.type.Type;
import org.hibernate.usertype.CompositeUserType;

/**
 * Hibernate CompositeUserType that can be used to persist {@link X509Certificate}.
 * 
 * @author Martijn Brinkers
 *
 */
public class X509CertificateUserType implements CompositeUserType {
    private static final int NOT_BEFORE_COLUMN = 0;
    private static final int NOT_AFTER_COLUMN = 1;
    private static final int ISSUER_COLUMN = 2;
    private static final int ISSUER_FRIENDLY_COLUMN = 3;
    private static final int SERIAL_NUMBER_COLUMN = 4;
    private static final int SUBJECT_KEY_IDENT_COLUMN = 5;
    private static final int SUBJECT_COLUMN = 6;
    private static final int SUBJECT_FRIENDLY_COLUMN = 7;
    private static final int CERTIFICATE_COLUMN = 8;
    private static final int THUMBPRINT_COLUMN = 9;

    /*
     * Subject and Issuer DN will be stored as CLOB because
     * there is no maximum size for a DN
     */
    private static final Type[] PROPERTY_TYPES = { Hibernate.TIMESTAMP, /* notBefore */
            Hibernate.TIMESTAMP, /* notAfter */
            Hibernate.TEXT, /* issuer */
            Hibernate.TEXT, /* issuerFriendly */
            Hibernate.STRING, /* serial */
            Hibernate.TEXT, /* subjectKeyIdentifier */
            Hibernate.TEXT, /* subject */
            Hibernate.TEXT, /* subjectFriendly */
            Hibernate.BINARY, /* certificate */
            Hibernate.STRING, /* thumbprint */
    };

    private static final String[] PROPERTY_NAMES = { "notBefore", "notAfter", "issuer", "issuerFriendly", "serial",
            "subjectKeyIdentifier", "subject", "subjectFriendly", "certificate", "thumbprint" };

    @Override
    public Object assemble(Serializable cached, SessionImplementor session, Object owner)
            throws HibernateException {
        return deepCopy(cached);
    }

    @Override
    public Object deepCopy(Object value) throws HibernateException {
        if (value == null) {
            return null;
        }

        if (!(value instanceof X509Certificate)) {
            throw new IllegalArgumentException("Object is not a X509Certificate.");
        }

        X509Certificate original = (X509Certificate) value;

        X509Certificate copy = null;

        try {
            byte[] encodedCert = original.getEncoded();

            CertificateFactory factory = SecurityFactoryFactory.getSecurityFactory()
                    .createCertificateFactory("X.509");

            copy = (X509Certificate) factory.generateCertificate(new ByteArrayInputStream(encodedCert));
        } catch (CertificateException e) {
            throw new HibernateException(e);
        } catch (NoSuchProviderException e) {
            throw new HibernateException(e);
        }

        return copy;
    }

    @Override
    public Serializable disassemble(Object value, SessionImplementor arg1) throws HibernateException {
        return (Serializable) deepCopy(value);
    }

    @Override
    public boolean equals(Object o1, Object o2) throws HibernateException {
        if (o1 == o2) {
            return true;
        }

        if ((o1 == null) || (o2 == null)) {
            return false;
        }

        /* fall back to X509Certificate.equals */
        return o1.equals(o2);
    }

    /* we must override hashCode because we override equals */
    @Override
    public int hashCode(Object object) throws HibernateException {
        return object.hashCode();
    }

    @Override
    public String[] getPropertyNames() {
        return PROPERTY_NAMES;
    }

    @Override
    public Type[] getPropertyTypes() {
        return PROPERTY_TYPES;
    }

    /*
     * Helper function to provide a work-around (if enabled) for a Outlook 2010 'bug'. Outlook 2010
     * uses a non-standard way to encode the Subject Key Identifier (SKI) and adds an SKI to a CMS 
     * Recipient Identifier even when the certificate used for encryption does not contain a SKI. 
     * This is clearly non RFC compliant. A workaround is to always add the SKI to the database
     * when the certificate does not have a SKI. 
     * 
     * For info why this workaround is needed see: https://bugzilla.mozilla.org/show_bug.cgi?id=559243 and
     * http://www.ietf.org/mail-archive/web/smime/current/msg18730.html
     */
    private String getSubjectKeyIdentifierHex(X509CertificateInspector inspector) throws IOException {
        String ski = inspector.getSubjectKeyIdentifierHex();

        if (ski == null && SecurityConstants.isOutlook2010SKIWorkaroundEnabled()) {
            ski = HexUtils.hexEncode(inspector.calculateSubjectKeyIdentifierMicrosoft());
        }

        return ski;
    }

    @Override
    public Object getPropertyValue(Object component, int property) throws HibernateException {
        if (component == null) {
            return null;
        }

        if (!(component instanceof X509Certificate)) {
            throw new IllegalArgumentException("Object is not a X509Certificate.");
        }

        X509Certificate certificate = (X509Certificate) component;

        try {
            X509CertificateInspector inspector = new X509CertificateInspector(certificate);

            switch (property) {
            case NOT_BEFORE_COLUMN:
                return certificate.getNotBefore();
            case NOT_AFTER_COLUMN:
                return certificate.getNotAfter();
            case ISSUER_COLUMN:
                return inspector.getIssuerCanonical();
            case ISSUER_FRIENDLY_COLUMN:
                return inspector.getIssuerFriendly();
            case SERIAL_NUMBER_COLUMN:
                return inspector.getSerialNumberHex();
            case SUBJECT_KEY_IDENT_COLUMN:
                return getSubjectKeyIdentifierHex(inspector);
            case SUBJECT_COLUMN:
                return inspector.getSubjectCanonical();
            case SUBJECT_FRIENDLY_COLUMN:
                return inspector.getSubjectFriendly();
            case CERTIFICATE_COLUMN:
                return certificate.getEncoded();
            case THUMBPRINT_COLUMN:
                return inspector.getThumbprint();
            }
        } catch (CertificateEncodingException e) {
            throw new HibernateException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new HibernateException(e);
        } catch (NoSuchProviderException e) {
            throw new HibernateException(e);
        } catch (CertificateParsingException e) {
            throw new HibernateException(e);
        } catch (IOException e) {
            throw new HibernateException(e);
        }

        return null;
    }

    @Override
    public boolean isMutable() {
        /* X509Certificate is immutable */
        return false;
    }

    @Override
    public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner)
            throws HibernateException, SQLException {
        X509Certificate certificate = null;

        byte[] encodedCertificate = rs.getBytes(names[CERTIFICATE_COLUMN]);

        if (!rs.wasNull() && encodedCertificate != null) {
            try {
                CertificateFactory factory = SecurityFactoryFactory.getSecurityFactory()
                        .createCertificateFactory("X.509");

                certificate = (X509Certificate) factory
                        .generateCertificate(new ByteArrayInputStream(encodedCertificate));
            } catch (CertificateException e) {
                throw new HibernateException(e);
            } catch (NoSuchProviderException e) {
                throw new HibernateException(e);
            }
        }

        return certificate;
    }

    @Override
    public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session)
            throws HibernateException, SQLException {
        try {
            Date notBefore = null;
            Date notafter = null;
            String issuer = null;
            String issuerFriendly = null;
            String serial = null;
            String subjectKeyIdentifier = null;
            String subject = null;
            String subjectFriendly = null;
            byte[] encodedCert = null;
            String thumbprint = null;

            if (value != null) {
                if (!(value instanceof X509Certificate)) {
                    throw new IllegalArgumentException("Object is not a X509Certificate.");
                }

                X509Certificate certificate = (X509Certificate) value;

                X509CertificateInspector inspector = new X509CertificateInspector(certificate);

                notBefore = certificate.getNotBefore();
                notafter = certificate.getNotAfter();
                issuer = inspector.getIssuerCanonical();
                issuerFriendly = inspector.getIssuerFriendly();
                serial = inspector.getSerialNumberHex();
                subjectKeyIdentifier = getSubjectKeyIdentifierHex(inspector);
                subject = inspector.getSubjectCanonical();
                subjectFriendly = inspector.getSubjectFriendly();
                encodedCert = certificate.getEncoded();
                thumbprint = inspector.getThumbprint();
            }

            Hibernate.TIMESTAMP.nullSafeSet(st, notBefore, index + NOT_BEFORE_COLUMN);
            Hibernate.TIMESTAMP.nullSafeSet(st, notafter, index + NOT_AFTER_COLUMN);
            Hibernate.STRING.nullSafeSet(st, issuer, index + ISSUER_COLUMN);
            Hibernate.STRING.nullSafeSet(st, issuerFriendly, index + ISSUER_FRIENDLY_COLUMN);
            Hibernate.STRING.nullSafeSet(st, serial, index + SERIAL_NUMBER_COLUMN);
            Hibernate.STRING.nullSafeSet(st, subjectKeyIdentifier, index + SUBJECT_KEY_IDENT_COLUMN);
            Hibernate.STRING.nullSafeSet(st, subject, index + SUBJECT_COLUMN);
            Hibernate.STRING.nullSafeSet(st, subjectFriendly, index + SUBJECT_FRIENDLY_COLUMN);
            Hibernate.BINARY.nullSafeSet(st, encodedCert, index + CERTIFICATE_COLUMN);
            Hibernate.STRING.nullSafeSet(st, thumbprint, index + THUMBPRINT_COLUMN);
        } catch (CertificateEncodingException e) {
            throw new HibernateException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new HibernateException(e);
        } catch (NoSuchProviderException e) {
            throw new HibernateException(e);
        } catch (CertificateParsingException e) {
            throw new HibernateException(e);
        } catch (IOException e) {
            throw new HibernateException(e);
        }
    }

    @Override
    public Object replace(Object original, Object target, SessionImplementor session, Object owner)
            throws HibernateException {
        return original;
    }

    @Override
    @SuppressWarnings("rawtypes")
    public Class returnedClass() {
        return X509Certificate.class;
    }

    @Override
    public void setPropertyValue(Object comnponent, int property, Object value) throws HibernateException {
        /* X509Certificate is immutable */
    }
}