mitm.common.tools.CreateCA.java Source code

Java tutorial

Introduction

Here is the source code for mitm.common.tools.CreateCA.java

Source

/*
 * Copyright (c) 2008-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.tools;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Date;

import javax.security.auth.x500.X500Principal;

import jline.ConsoleReader;
import mitm.common.security.SecurityFactory;
import mitm.common.security.SecurityFactoryFactory;
import mitm.common.security.certificate.AltNamesBuilder;
import mitm.common.security.certificate.SerialNumberGenerator;
import mitm.common.security.certificate.X500PrincipalBuilder;
import mitm.common.security.certificate.X509CertificateBuilder;
import mitm.common.security.certificate.impl.StandardSerialNumberGenerator;

import org.apache.commons.lang.time.DateUtils;
import org.apache.log4j.PropertyConfigurator;
import org.bouncycastle.asn1.x509.GeneralNames;

public class CreateCA {
    private final SecurityFactory securityFactory;
    private final SecureRandom randomSource;
    private final SerialNumberGenerator serialNumberGenerator;

    private X509Certificate rootCertificate;
    private X509Certificate intermediateCertificate;

    private KeyPair rootKeyPair;
    private KeyPair intermediateKeyPair;

    public CreateCA() throws NoSuchAlgorithmException, NoSuchProviderException, KeyStoreException {
        securityFactory = SecurityFactoryFactory.getSecurityFactory();

        randomSource = securityFactory.createSecureRandom();

        serialNumberGenerator = new StandardSerialNumberGenerator();
    }

    private void generateRoot() throws Exception {
        X509CertificateBuilder certificateBuilder = securityFactory.createX509CertificateBuilder();

        KeyPairGenerator keyPairGenerator = securityFactory.createKeyPairGenerator("RSA");

        keyPairGenerator.initialize(2048, randomSource);

        rootKeyPair = keyPairGenerator.generateKeyPair();

        X500PrincipalBuilder issuerBuilder = new X500PrincipalBuilder();

        String email = "martijn@mitm.nl";

        issuerBuilder.setCommonName("MITM Root");
        issuerBuilder.setCountryCode("NL");
        issuerBuilder.setEmail(email);
        issuerBuilder.setLocality("Amsterdam");
        issuerBuilder.setState("NH");

        AltNamesBuilder altNamesBuider = new AltNamesBuilder();

        altNamesBuider.setRFC822Names(email);

        X500Principal issuer = issuerBuilder.buildPrincipal();
        GeneralNames altNames = altNamesBuider.buildAltNames();

        Date now = new Date();

        certificateBuilder.setSubject(issuer);
        certificateBuilder.setIssuer(issuer);
        certificateBuilder.setAltNames(altNames, true);
        certificateBuilder.setNotBefore(now);
        certificateBuilder.setNotAfter(DateUtils.addYears(now, 20));
        certificateBuilder.setPublicKey(rootKeyPair.getPublic());
        certificateBuilder.setSerialNumber(serialNumberGenerator.generate());
        certificateBuilder.setSignatureAlgorithm("SHA1WithRSAEncryption");
        certificateBuilder.setIsCA(true, true);
        certificateBuilder.addSubjectKeyIdentifier(true);

        /*
         * generate self signed certificate
         */
        rootCertificate = certificateBuilder.generateCertificate(rootKeyPair.getPrivate(), null);
    }

    private void generateIntermediate() throws Exception {
        X509CertificateBuilder certificateBuilder = securityFactory.createX509CertificateBuilder();

        KeyPairGenerator keyPairGenerator = securityFactory.createKeyPairGenerator("RSA");

        keyPairGenerator.initialize(2048, randomSource);

        intermediateKeyPair = keyPairGenerator.generateKeyPair();

        X500PrincipalBuilder issuerBuilder = new X500PrincipalBuilder();

        String email = "martijn@mitm.nl";

        issuerBuilder.setCommonName("MITM Intermediate");
        issuerBuilder.setCountryCode("NL");
        issuerBuilder.setEmail(email);
        issuerBuilder.setLocality("Amsterdam");
        issuerBuilder.setState("NH");

        AltNamesBuilder altNamesBuider = new AltNamesBuilder();

        altNamesBuider.setRFC822Names(email);

        X500Principal issuer = issuerBuilder.buildPrincipal();
        GeneralNames altNames = altNamesBuider.buildAltNames();

        Date now = new Date();

        certificateBuilder.setSubject(issuer);
        certificateBuilder.setIssuer(rootCertificate.getSubjectX500Principal());
        certificateBuilder.setAltNames(altNames, true);
        certificateBuilder.setNotBefore(now);
        certificateBuilder.setNotAfter(DateUtils.addYears(now, 20));
        certificateBuilder.setPublicKey(intermediateKeyPair.getPublic());
        certificateBuilder.setSerialNumber(serialNumberGenerator.generate());
        certificateBuilder.setSignatureAlgorithm("SHA1WithRSAEncryption");
        certificateBuilder.setIsCA(true, true);
        certificateBuilder.addSubjectKeyIdentifier(true);

        intermediateCertificate = certificateBuilder.generateCertificate(rootKeyPair.getPrivate(),
                intermediateCertificate);
    }

    public void generateCA(String password, File p12File) throws Exception {
        KeyStore keyStore = securityFactory.createKeyStore("PKCS12");

        keyStore.load(null);

        generateRoot();
        generateIntermediate();

        keyStore.setKeyEntry("root", rootKeyPair.getPrivate(), null, new Certificate[] { rootCertificate });

        keyStore.setKeyEntry("intermediate", intermediateKeyPair.getPrivate(), null,
                new Certificate[] { intermediateCertificate, rootCertificate });

        FileOutputStream output = new FileOutputStream(p12File);

        keyStore.store(output, password.toCharArray());

        output.close();
    }

    public static void main(String[] args) throws Exception {
        PropertyConfigurator.configure("conf/log4j.properties");

        if (args.length != 1) {
            System.err.println("p12 file expected.");

            return;
        }

        System.out.println("Please enter your password: ");

        ConsoleReader consoleReader = new ConsoleReader(new FileInputStream(FileDescriptor.in),
                new PrintWriter(System.err));

        String password = consoleReader.readLine(new Character('*'));

        CreateCA createCA = new CreateCA();

        File p12File = new File(args[0]);

        createCA.generateCA(password, p12File);

        System.out.println("CA generated and written to " + p12File.getAbsolutePath());
    }
}