mitm.common.security.ca.hibernate.CertificateRequestStoreImplTest.java Source code

Java tutorial

Introduction

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

Source

/*
 * Copyright (c) 2010-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.security.ca.hibernate;

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

import java.io.File;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.List;

import javax.security.auth.x500.X500Principal;

import mitm.common.hibernate.HibernateSessionSource;
import mitm.common.hibernate.SessionManagedAutoCommitProxyFactory;
import mitm.common.hibernate.SessionManager;
import mitm.common.hibernate.SessionManagerImpl;
import mitm.common.hibernate.StandardHibernateSessionSourceImpl;
import mitm.common.hibernate.annotations.StartTransaction;
import mitm.common.reflection.ProxyFactoryException;
import mitm.common.security.KeyEncoderException;
import mitm.common.security.ca.CertificateRequest;
import mitm.common.security.ca.CertificateRequestStore;
import mitm.common.security.ca.Match;
import mitm.common.security.certificate.X500PrincipalBuilder;
import mitm.common.security.crypto.Encryptor;
import mitm.common.security.crypto.impl.PasswordBasedEncryptor;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.log4j.BasicConfigurator;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class CertificateRequestStoreImplTest {
    private static final File hibernateConfig = new File("test/resources/hibernate.cfg.xml");

    private static SessionManager sessionManager;
    private static Encryptor encryptor;
    private static CertificateRequestStore store;

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        BasicConfigurator.configure();

        encryptor = new PasswordBasedEncryptor("test");

        HibernateSessionSource sessionSource = new StandardHibernateSessionSourceImpl(hibernateConfig);

        sessionManager = new SessionManagerImpl(sessionSource);
    }

    @Before
    public void setup() throws Exception {
        store = new CertificateRequestStoreImpl(sessionManager);

        AutoTransactDelegator.createProxy().deleteAll();
    }

    protected static class AutoTransactDelegator {

        public AutoTransactDelegator() {
            // required
        }

        protected static AutoTransactDelegator createProxy() throws ProxyFactoryException, NoSuchMethodException {
            AutoTransactDelegator autoTransactDelegator = new SessionManagedAutoCommitProxyFactory<AutoTransactDelegator>(
                    AutoTransactDelegator.class, sessionManager).createProxy();

            return autoTransactDelegator;
        }

        @StartTransaction
        public void deleteAll() {
            List<? extends CertificateRequest> all = store.getAllRequests(null, null);

            for (CertificateRequest request : all) {
                store.deleteRequest(request.getID());
            }

            assertEquals(0, store.getSize());
        }

        public CertificateRequest addRequest(X500Principal subject, String email, int validity,
                String signatureAlgorithm, String crlDistPoint, String certificateHandlerName, byte[] data,
                Date lastUpdated, String lastMessage, KeyPair keyPair) throws KeyEncoderException {
            return addRequest(null, subject, email, validity, signatureAlgorithm, crlDistPoint,
                    certificateHandlerName, data, lastUpdated, lastMessage, keyPair);
        }

        @StartTransaction
        public CertificateRequest addRequest(Date created, X500Principal subject, String email, int validity,
                String signatureAlgorithm, String crlDistPoint, String certificateHandlerName, byte[] data,
                Date lastUpdated, String lastMessage, KeyPair keyPair) throws KeyEncoderException {
            CertificateRequestEntity request = created != null
                    ? new CertificateRequestEntity(certificateHandlerName, created)
                    : new CertificateRequestEntity(certificateHandlerName);

            request.setSubject(subject);
            request.setEmail(email);
            request.setValidity(validity);
            request.setSignatureAlgorithm(signatureAlgorithm);
            request.setCRLDistributionPoint(crlDistPoint);
            request.setData(data);
            request.setLastUpdated(lastUpdated);
            request.setLastMessage(lastMessage);
            request.setKeyPair(keyPair, encryptor);

            store.addRequest(request);

            return request;
        }

        @StartTransaction
        public List<? extends CertificateRequest> getRequestsByEmail(String email, Match match, Integer firstResult,
                Integer maxResults) {
            return store.getRequestsByEmail(email, match, firstResult, maxResults);
        }

        @StartTransaction
        public List<? extends CertificateRequest> getAllRequests(Integer firstResult, Integer maxResults) {
            return store.getAllRequests(firstResult, maxResults);
        }

        @StartTransaction
        public void updateRequest(Long id, byte[] data, Date lastUpdated, String lastMessage, Date nextUpdate) {
            CertificateRequest request = store.getRequest(id);

            assertNotNull(request);

            request.setData(data);
            request.setLastUpdated(lastUpdated);
            request.setLastMessage(lastMessage);
            request.setNextUpdate(nextUpdate);
        }

        @StartTransaction
        public CertificateRequest getRequest(Long id) {
            return store.getRequest(id);
        }

        @StartTransaction
        public CertificateRequest getNextRequest() {
            return store.getNextRequest();
        }

        @StartTransaction
        public int getSize() {
            return store.getSize();
        }

        @StartTransaction
        public int getSizeByEmail(String email, Match match) {
            return store.getSizeByEmail(email, match);
        }
    }

    private KeyPair generateKeyPair() throws NoSuchAlgorithmException {
        return KeyPairGenerator.getInstance("RSA").generateKeyPair();
    }

    @Test
    public void testGetSizeByEmail() throws Exception {
        AutoTransactDelegator delegator = AutoTransactDelegator.createProxy();

        delegator.addRequest(new Date(), null, "test@example.com", 0, null, null, "dummy", null, null, null, null);

        delegator.addRequest(new Date(), null, "other@example.com", 0, null, null, "dummy", null, null, null, null);

        delegator.addRequest(new Date(), null, "test@example.com", 0, null, null, "dummy", null, null, null, null);

        delegator.addRequest(new Date(), null, " test@EXAMPLE.com ", 0, null, null, "dummy", null, null, null,
                null);

        delegator.addRequest(new Date(), null, "andanother@example.com", 0, null, null, "dummy", null, null, null,
                null);

        assertEquals(3, delegator.getSizeByEmail("test@example.com", Match.EXACT));
        assertEquals(3, delegator.getSizeByEmail(" TEST@example.COM ", Match.EXACT));
        assertEquals(1, delegator.getSizeByEmail("other@example.com", Match.EXACT));
        assertEquals(5, delegator.getSizeByEmail("example", Match.LIKE));
    }

    @Test
    public void testGetAllRequests() throws Exception {
        AutoTransactDelegator delegator = AutoTransactDelegator.createProxy();

        int total = 10;

        for (int i = 0; i < total; i++) {
            delegator.addRequest(new Date(), null, Integer.toString(i) + "@example.com", 0, null, null, "dummy",
                    null, null, null, null);
        }

        assertEquals(total, delegator.getSize());

        List<? extends CertificateRequest> all = delegator.getAllRequests(null, null);

        assertEquals(total, all.size());

        for (int i = 0; i < total; i++) {
            assertEquals(Integer.toString(i) + "@example.com", all.get(i).getEmail());
        }

        int start = 0;
        int max = 3;

        all = delegator.getAllRequests(start, max);
        assertEquals(Math.min(total - start, max), all.size());

        for (int i = 0; i < Math.min(total - start, max); i++) {
            assertEquals(Integer.toString(i + start) + "@example.com", all.get(i).getEmail());
        }

        start = 4;
        max = 2;

        all = delegator.getAllRequests(start, max);
        assertEquals(Math.min(total - start, max), all.size());

        for (int i = 0; i < Math.min(total - start, max); i++) {
            assertEquals(Integer.toString(i + start) + "@example.com", all.get(i).getEmail());
        }

        start = 7;
        max = 100;

        all = delegator.getAllRequests(start, max);
        assertEquals(Math.min(total - start, max), all.size());

        for (int i = 0; i < Math.min(total - start, max); i++) {
            assertEquals(Integer.toString(i + start) + "@example.com", all.get(i).getEmail());
        }

        start = 100;
        max = 100;

        all = delegator.getAllRequests(start, max);
        assertEquals(0, all.size());
    }

    @Test
    public void testGetNextRequest() throws Exception {
        AutoTransactDelegator delegator = AutoTransactDelegator.createProxy();

        Date now = new Date();

        Date newer = DateUtils.addDays(now, 1);

        delegator.addRequest(newer, null, "2@example.com", 0, null, null, "dummy", null, null, null, null);

        delegator.addRequest(now, null, "1@example.com", 0, null, null, "dummy", null, null, null, null);

        CertificateRequest request = delegator.getNextRequest();

        assertNotNull(request);
        assertEquals("1@example.com", request.getEmail());

        request = delegator.getNextRequest();

        assertNotNull(request);
        assertEquals("1@example.com", request.getEmail());

        delegator.updateRequest(request.getID(), new byte[] { 1, 2, 3 }, new Date(), "message",
                DateUtils.addSeconds(new Date(), 5));

        request = delegator.getNextRequest();

        assertNotNull(request);
        assertEquals("2@example.com", request.getEmail());

        request = delegator.getNextRequest();

        assertNotNull(request);
        assertEquals("2@example.com", request.getEmail());

        delegator.updateRequest(request.getID(), new byte[] { 1, 2, 3 }, new Date(), "message",
                DateUtils.addSeconds(new Date(), 6));

        request = delegator.getNextRequest();

        assertNull(request);
    }

    @Test
    public void testUpdate() throws Exception {
        AutoTransactDelegator delegator = AutoTransactDelegator.createProxy();

        Date now = new Date();

        CertificateRequest request = delegator.addRequest(now, null, "test@example.com", 1, null, null, "dummy",
                null, null, null, null);

        assertNotNull(request.getID());
        assertNull(request.getData());
        assertNull(request.getLastUpdated());
        assertNull(request.getLastMessage());

        Date updated = DateUtils.addDays(now, 1);

        delegator.updateRequest(request.getID(), new byte[] { 1, 2, 3 }, updated, "message", null);

        request = delegator.getRequest(request.getID());

        assertEquals("test@example.com", request.getEmail());
        assertTrue(ArrayUtils.isEquals(new byte[] { 1, 2, 3 }, request.getData()));
        assertEquals(updated, request.getLastUpdated());
        assertEquals("message", request.getLastMessage());
    }

    @Test
    public void testSorting() throws Exception {
        AutoTransactDelegator delegator = AutoTransactDelegator.createProxy();

        Date now = new Date();

        Date old = DateUtils.addDays(now, -1);

        delegator.addRequest(now, null, "now@example.com", 365, null, null, "dummy", null, new Date(), null, null);

        delegator.addRequest(old, null, "old@example.com", 365, null, null, "dummy", null, new Date(), null, null);

        List<? extends CertificateRequest> found = delegator.getAllRequests(null, null);

        assertEquals(2, found.size());

        CertificateRequest request = found.get(0);
        assertEquals("old@example.com", request.getEmail());
        assertNull(request.getKeyPair(encryptor));

        request = found.get(1);
        assertEquals("now@example.com", request.getEmail());
    }

    @Test
    public void testAddRequest() throws Exception {
        AutoTransactDelegator delegator = AutoTransactDelegator.createProxy();

        X500PrincipalBuilder builder = new X500PrincipalBuilder();

        builder.setCommonName("john doe");
        builder.setEmail("johndoe@example.com");

        KeyPair keyPair = generateKeyPair();

        delegator.addRequest(builder.buildPrincipal(), "test@example.com", 365, "SHA1", "http://example.com",
                "dummy", new byte[] { 1, 2, 3 }, new Date(), "Some message", keyPair);

        List<? extends CertificateRequest> found = delegator.getRequestsByEmail("test@example.com", null, null,
                null);

        assertEquals(1, found.size());

        CertificateRequest request = found.get(0);

        KeyPair keyPairCopy = request.getKeyPair(encryptor);

        assertNotNull(keyPairCopy);
        assertEquals(keyPair.getPublic(), keyPairCopy.getPublic());
        assertEquals(keyPair.getPrivate(), keyPairCopy.getPrivate());
    }

    @Test
    public void testGetKeyPairSpeedTest() throws Exception {
        AutoTransactDelegator delegator = AutoTransactDelegator.createProxy();

        KeyPair keyPair = generateKeyPair();

        CertificateRequest request = delegator.addRequest(null, "test@example.com", 365, "SHA1",
                "http://example.com", "dummy", new byte[] { 1, 2, 3 }, new Date(), "Some message", keyPair);

        long start = System.currentTimeMillis();

        int repeat = 100;

        for (int i = 0; i < repeat; i++) {
            KeyPair keyPairCopy = request.getKeyPair(encryptor);

            assertNotNull(keyPairCopy);
            assertEquals(keyPair.getPublic(), keyPairCopy.getPublic());
            assertEquals(keyPair.getPrivate(), keyPairCopy.getPrivate());
        }

        long diff = System.currentTimeMillis() - start;

        double perSecond = repeat * 1000.0 / diff;

        System.out.println("getKeyPair's/sec: " + perSecond);

        /*
         * NOTE: !!! can fail on a slower system. The speed depends on the system encryptor. If the default settings 
         * (like iteration count) have been changed this might be slower.
         * 
         * On my Quad CPU Q8300, should be about 500/sec
         */
        assertTrue("getKeyPair too slow. !!! this can fail on a slower system !!!", perSecond > 200);
    }

    @Test
    public void testAddDuplicateRequest() throws Exception {
        AutoTransactDelegator delegator = AutoTransactDelegator.createProxy();

        X500PrincipalBuilder builder = new X500PrincipalBuilder();

        builder.setCommonName("john doe");
        builder.setEmail("johndoe@example.com");

        KeyPair keyPair = generateKeyPair();

        Date date = new Date();

        delegator.addRequest(date, builder.buildPrincipal(), "test@example.com", 365, "SHA1", "http://example.com",
                "dummy", new byte[] { 1, 2, 3 }, new Date(), "Some message", keyPair);

        delegator.addRequest(date, builder.buildPrincipal(), "test@example.com", 365, "SHA1", "http://example.com",
                "dummy", new byte[] { 1, 2, 3 }, new Date(), "Some message", keyPair);

        List<? extends CertificateRequest> found = delegator.getRequestsByEmail("test@example.com", Match.EXACT,
                null, null);

        assertEquals(2, found.size());
    }

    @Test
    public void testAddRequestOnlyEmail() throws Exception {
        AutoTransactDelegator delegator = AutoTransactDelegator.createProxy();

        delegator.addRequest(null, "test@example.com", 365, null, null, "dummy", null, null, null, null);
    }
}