mitm.common.security.ca.SMIMEKeyAndCertificateIssuer.java Source code

Java tutorial

Introduction

Here is the source code for mitm.common.security.ca.SMIMEKeyAndCertificateIssuer.java

Source

/*
 * Copyright (c) 2009-2012, 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.security.ca;

import java.io.IOException;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;

import mitm.common.security.KeyAndCertificate;
import mitm.common.security.KeyAndCertificateImpl;
import mitm.common.security.SecurityFactory;
import mitm.common.security.SecurityFactoryFactory;
import mitm.common.security.SecurityFactoryFactoryException;
import mitm.common.security.certificate.AltNamesBuilder;
import mitm.common.security.certificate.CertificateBuilderException;
import mitm.common.security.certificate.ExtendedKeyUsageType;
import mitm.common.security.certificate.KeyUsageType;
import mitm.common.security.certificate.SerialNumberGenerator;
import mitm.common.security.certificate.X509CertificateBuilder;
import mitm.common.security.certificate.impl.StandardSerialNumberGenerator;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;

/**
 * Implementation of KeyAndCertificateIssuer that issues certificates only suitable for S/MIME.
 * 
 * @author Martijn Brinkers
 *
 */
public class SMIMEKeyAndCertificateIssuer implements KeyAndCertificateIssuer {
    /*
     * Factory used to create security object instances
     */
    private final SecurityFactory securityFactory;

    /*
     * Used by the KeyPairGenerator
     * 
     * Note: SecureRandom is not thread safe.
     */
    private final SecureRandom randomSource;

    public SMIMEKeyAndCertificateIssuer() throws CAException {
        try {
            securityFactory = SecurityFactoryFactory.getSecurityFactory();

            randomSource = securityFactory.createSecureRandom();
        } catch (NoSuchAlgorithmException e) {
            throw new CAException(e);
        } catch (NoSuchProviderException e) {
            throw new CAException(e);
        } catch (SecurityFactoryFactoryException e) {
            throw new CAException(e);
        }
    }

    /*
     * Note: Random source is not thread safe so we need to synchronize.
     */
    private synchronized KeyPair generateKeyPair(RequestParameters parameters)
            throws NoSuchAlgorithmException, NoSuchProviderException {
        KeyPairGenerator keyPairGenerator = securityFactory.createKeyPairGenerator("RSA");

        keyPairGenerator.initialize(parameters.getKeyLength(), randomSource);

        return keyPairGenerator.generateKeyPair();
    }

    @Override
    public KeyAndCertificate issueKeyAndCertificate(RequestParameters parameters, KeyAndCertificate signer)
            throws CAException {
        try {
            if (StringUtils.isBlank(parameters.getEmail())) {
                throw new CAException("email must be specified.");
            }

            if (parameters.getSubject() == null) {
                throw new CAException("subject must be specified.");
            }

            if (signer == null || signer.getCertificate() == null || signer.getPrivateKey() == null) {
                throw new CAException("issuer fields must be non-null.");
            }

            KeyPair keyPair = generateKeyPair(parameters);

            Set<KeyUsageType> keyUsage = new TreeSet<KeyUsageType>();

            keyUsage.add(KeyUsageType.DIGITALSIGNATURE);
            keyUsage.add(KeyUsageType.KEYENCIPHERMENT);

            Set<ExtendedKeyUsageType> extendedKeyUsage = new HashSet<ExtendedKeyUsageType>();

            extendedKeyUsage.add(ExtendedKeyUsageType.EMAILPROTECTION);
            extendedKeyUsage.add(ExtendedKeyUsageType.CLIENTAUTH);

            SerialNumberGenerator serialNumberGenerator = new StandardSerialNumberGenerator();

            BigInteger serialNumber = serialNumberGenerator.generate();

            AltNamesBuilder altNamesBuider = new AltNamesBuilder();

            altNamesBuider.setRFC822Names(parameters.getEmail());

            X509CertificateBuilder certificateBuilder = securityFactory.createX509CertificateBuilder();

            Date now = new Date();

            certificateBuilder.setAltNames(altNamesBuider.buildAltNames(), false);
            certificateBuilder.setSubject(parameters.getSubject());
            certificateBuilder.setIssuer(signer.getCertificate().getSubjectX500Principal());
            certificateBuilder.setKeyUsage(keyUsage, true);
            certificateBuilder.setExtendedKeyUsage(extendedKeyUsage, false);
            certificateBuilder.setNotBefore(DateUtils.addDays(now, -1));
            certificateBuilder.setNotAfter(DateUtils.addDays(now, parameters.getValidity()));
            certificateBuilder.setPublicKey(keyPair.getPublic());
            certificateBuilder.setSerialNumber(serialNumber);
            certificateBuilder.setSignatureAlgorithm(parameters.getSignatureAlgorithm());
            certificateBuilder.addSubjectKeyIdentifier(true);

            if (StringUtils.isNotBlank(parameters.getCRLDistributionPoint())) {
                certificateBuilder
                        .setCRLDistributionPoints(Collections.singleton(parameters.getCRLDistributionPoint()));
            }

            X509Certificate certificate = certificateBuilder.generateCertificate(signer.getPrivateKey(),
                    signer.getCertificate());

            return new KeyAndCertificateImpl(keyPair.getPrivate(), certificate);
        } catch (NoSuchAlgorithmException e) {
            throw new CAException(e);
        } catch (NoSuchProviderException e) {
            throw new CAException(e);
        } catch (CertificateBuilderException e) {
            throw new CAException(e);
        } catch (IllegalStateException e) {
            throw new CAException(e);
        } catch (IOException e) {
            throw new CAException(e);
        }
    }
}