mitm.common.security.certificate.impl.StandardX509CertificateBuilderTest.java Source code

Java tutorial

Introduction

Here is the source code for mitm.common.security.certificate.impl.StandardX509CertificateBuilderTest.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.security.certificate.impl;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.io.File;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.security.auth.x500.X500Principal;

import mitm.common.security.SecurityFactory;
import mitm.common.security.SecurityFactoryFactory;
import mitm.common.security.certificate.AltNamesBuilder;
import mitm.common.security.certificate.AltNamesInspector;
import mitm.common.security.certificate.CertificateUtils;
import mitm.common.security.certificate.ExtendedKeyUsageType;
import mitm.common.security.certificate.KeyUsageType;
import mitm.common.security.certificate.X500PrincipalBuilder;
import mitm.common.security.certificate.X509CertificateBuilder;
import mitm.common.security.certificate.X509CertificateInspector;
import mitm.common.security.crl.CRLDistributionPointsInspector;

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

public class StandardX509CertificateBuilderTest {
    private static final File tempDir = new File("test/tmp");

    private static SecurityFactory securityFactory;
    private static SecureRandom randomSource;

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        PropertyConfigurator.configure("conf/log4j.properties");

        securityFactory = SecurityFactoryFactory.getSecurityFactory();
        randomSource = securityFactory.createSecureRandom();
    }

    @Test
    public void testGenerateSelfSignedV3Certificate() throws Exception {
        X509CertificateBuilder certificateBuilder = new StandardX509CertificateBuilder("BC", "BC");

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

        keyPairGenerator.initialize(2048, randomSource);

        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        X500PrincipalBuilder issuerBuilder = new X500PrincipalBuilder();

        issuerBuilder.setCommonName("Martijn Brinkers");
        issuerBuilder.setCountryCode("NL");
        issuerBuilder.setEmail("test@example.com", "test2@example.com");
        issuerBuilder.setGivenName("Martijn");
        issuerBuilder.setSurname("Brinkers");
        issuerBuilder.setLocality("Amsterdam");
        issuerBuilder.setOrganisation("None");
        issuerBuilder.setState("NH");

        AltNamesBuilder altNamesBuider = new AltNamesBuilder();

        altNamesBuider.setRFC822Names("m.brinkers@pobox.com");
        altNamesBuider.setDNSNames("example.com");

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

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

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

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

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

        Date notBefore = DateUtils.addHours(new Date(), -1);
        Date notAfter = DateUtils.addYears(new Date(), 10);

        certificateBuilder.setSubject(issuer);
        certificateBuilder.setIssuer(issuer);
        certificateBuilder.setAltNames(altNames, true);
        certificateBuilder.setKeyUsage(keyUsage, true);
        certificateBuilder.setExtendedKeyUsage(extendedKeyUsage, true);
        certificateBuilder.setNotBefore(notBefore);
        certificateBuilder.setNotAfter(notAfter);
        certificateBuilder.setPublicKey(keyPair.getPublic());
        certificateBuilder.setSerialNumber(new BigInteger("1"));
        certificateBuilder.setSignatureAlgorithm("SHA256WithRSA");
        certificateBuilder.setIsCA(true, true /* critical */);
        certificateBuilder.setPathLengthConstraint(5);

        Set<String> crlDistPoints = new HashSet<String>();
        crlDistPoints.add("http://example.com");
        crlDistPoints.add("123");

        certificateBuilder.setCRLDistributionPoints(crlDistPoints);

        X509Certificate certificate = certificateBuilder.generateCertificate(keyPair.getPrivate(), null);

        assertNotNull(certificate);

        File file = new File(tempDir, "testGenerateSelfSignedV3Certificate.cer");

        CertificateUtils.writeCertificate(certificate, file);

        X509CertificateInspector certInspector = new X509CertificateInspector(certificate);

        assertEquals(
                "EMAILADDRESS=test2@example.com, EMAILADDRESS=test@example.com, GIVENNAME=Martijn, "
                        + "SURNAME=Brinkers, CN=Martijn Brinkers, O=None, L=Amsterdam, ST=NH, C=NL",
                certInspector.getSubjectFriendly());

        assertEquals(certInspector.getIssuerFriendly(), certInspector.getSubjectFriendly());

        AltNamesInspector altNamesInspector = new AltNamesInspector(certificate.getSubjectAlternativeNames());

        List<String> rFC822Names = altNamesInspector.getRFC822Names();

        assertEquals(1, rFC822Names.size());
        assertEquals("m.brinkers@pobox.com", rFC822Names.get(0));

        List<String> dNSNames = altNamesInspector.getDNSNames();

        assertEquals(1, dNSNames.size());
        assertEquals("example.com", dNSNames.get(0));

        assertEquals(3, certInspector.getKeyUsage().size());
        assertTrue(certInspector.getKeyUsage().contains(KeyUsageType.DIGITALSIGNATURE));
        assertTrue(certInspector.getKeyUsage().contains(KeyUsageType.KEYENCIPHERMENT));
        assertTrue(certInspector.getKeyUsage().contains(KeyUsageType.NONREPUDIATION));

        assertEquals(2, certInspector.getExtendedKeyUsage().size());
        assertTrue(certInspector.getExtendedKeyUsage().contains(ExtendedKeyUsageType.CLIENTAUTH));
        assertTrue(certInspector.getExtendedKeyUsage().contains(ExtendedKeyUsageType.EMAILPROTECTION));

        // we cannot compare the dates because of encoding we loose some detail so check if within 1 sec
        assertTrue(Math.abs(notAfter.getTime() - certificate.getNotAfter().getTime()) < 1000);
        assertTrue(Math.abs(notBefore.getTime() - certificate.getNotBefore().getTime()) < 1000);

        assertEquals("1", certInspector.getSerialNumberHex());

        assertEquals("SHA256WITHRSA", certificate.getSigAlgName());

        assertTrue(certInspector.isCA());
        assertEquals(5, certInspector.getBasicConstraints().getPathLenConstraint().intValue());

        Set<String> crlDistPointsCert = CRLDistributionPointsInspector
                .getURIDistributionPointNames(certInspector.getCRLDistibutionPoints());

        assertTrue(crlDistPointsCert.contains("http://example.com"));
        assertTrue(crlDistPointsCert.contains("123"));
    }
}