mitm.common.security.ca.handlers.ejbca.ws.EjbcaWSClient.java Source code

Java tutorial

Introduction

Here is the source code for mitm.common.security.ca.handlers.ejbca.ws.EjbcaWSClient.java

Source

/*
 * Copyright (c) 2011-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.handlers.ejbca.ws;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Collection;

import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import javax.xml.namespace.QName;

import mitm.common.security.SecurityFactory;
import mitm.common.security.SecurityFactoryFactory;
import mitm.common.security.certificate.CertificateUtils;
import mitm.common.security.certificate.X500PrincipalBuilder;
import mitm.common.security.certificate.X500PrincipalUtils;
import mitm.common.security.keystore.KeyStoreLoader;
import mitm.common.util.Base64Utils;

import org.apache.commons.collections.CollectionUtils;
import org.apache.cxf.configuration.jsse.TLSClientParameters;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.log4j.BasicConfigurator;
import org.apache.xml.security.utils.Base64;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.pkcs.PKCS10CertificationRequest;
import org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder;

/**
 * Some test client used for locally testing the EJBCA webservice.
 * 
 * @author Martijn Brinkers
 */
public final class EjbcaWSClient {

    private static final QName SERVICE_NAME = new QName("http://ws.protocol.core.ejbca.org/", "EjbcaWSService");

    private EjbcaWSClient() {
    }

    private static ContentSigner getContentSigner(String signatureAlgorithm, PrivateKey privateKey)
            throws OperatorCreationException {
        JcaContentSignerBuilder contentSignerBuilder = new JcaContentSignerBuilder(signatureAlgorithm);

        contentSignerBuilder.setProvider("BC");

        return contentSignerBuilder.build(privateKey);
    }

    public static void main(String args[]) throws Exception {
        BasicConfigurator.configure();

        JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();

        factory.setServiceClass(EjbcaWS.class);
        factory.setAddress("https://192.168.178.113:8443/ejbca/ejbcaws/ejbcaws");
        factory.setServiceName(SERVICE_NAME);

        EjbcaWS client = (EjbcaWS) factory.create();

        Client proxy = ClientProxy.getClient(client);
        HTTPConduit conduit = (HTTPConduit) proxy.getConduit();
        TLSClientParameters tlsClientParameters = new TLSClientParameters();

        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());

        java.security.KeyStore keyStore = java.security.KeyStore.getInstance("PKCS12");
        InputStream keyInput = new FileInputStream("/home/martijn/temp/superadmin.p12");

        String password = "ejbca";

        keyStore.load(keyInput, password.toCharArray());
        keyInput.close();
        keyManagerFactory.init(keyStore, password.toCharArray());

        KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();

        tlsClientParameters.setDisableCNCheck(true);

        tlsClientParameters.setKeyManagers(keyManagers);

        X509TrustManager trustAll = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString)
                    throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString)
                    throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());

        trustManagerFactory.init(new KeyStoreLoader().loadKeyStore(new File("/home/martijn/temp/truststore.jks"),
                "changeit".toCharArray()));

        tlsClientParameters.setTrustManagers(new TrustManager[] { trustAll });
        //tlsClientParameters.setTrustManagers(trustManagerFactory.getTrustManagers());

        conduit.setTlsClientParameters(tlsClientParameters);

        System.out.println(client.getEjbcaVersion());

        UserDataVOWS userData = new UserDataVOWS();

        userData.setEmail("test@example.com");
        userData.setUsername("test@example.com");
        //userData.setPassword("test@example.com");
        userData.setSubjectDN("CN=test@example.com");
        userData.setSubjectAltName("rfc822Name=test@example.com");
        userData.setEndEntityProfileName("test");
        userData.setCaName("AdminCA1");
        userData.setCertificateProfileName("ENDUSER");
        userData.setStatus(EJBCAConst.STATUS_NEW);
        userData.setTokenType(EJBCAConst.TOKEN_TYPE_USERGENERATED);

        try {
            //client.editUser(userData);

            SecurityFactory securityFactory = SecurityFactoryFactory.getSecurityFactory();

            SecureRandom randomSource = securityFactory.createSecureRandom();

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

            keyPairGenerator.initialize(2048, randomSource);

            KeyPair keyPair = keyPairGenerator.generateKeyPair();

            X500PrincipalBuilder builder = new X500PrincipalBuilder();

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

            PKCS10CertificationRequestBuilder requestBuilder = new PKCS10CertificationRequestBuilder(
                    X500PrincipalUtils.toX500Name(builder.buildPrincipal()),
                    SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()));

            PKCS10CertificationRequest pkcs10 = requestBuilder
                    .build(getContentSigner("SHA1WithRSA", keyPair.getPrivate()));

            String base64PKCS10 = Base64Utils.encode(pkcs10.getEncoded());

            CertificateResponse certificateResponse = client.certificateRequest(userData, base64PKCS10,
                    EJBCAConst.CERT_REQ_TYPE_PKCS10, null, EJBCAConst.RESPONSETYPE_CERTIFICATE);

            if (certificateResponse != null && certificateResponse.getData() != null) {
                /*
                 * The result is a base64 encoded certificate 
                 */
                Collection<X509Certificate> certificates = CertificateUtils.readX509Certificates(
                        new ByteArrayInputStream(Base64.decode(certificateResponse.getData())));

                if (CollectionUtils.isNotEmpty(certificates)) {
                    for (X509Certificate certificate : certificates) {
                        System.out.println(certificate);
                    }
                } else {
                    System.out.println("No certificates found");
                }
            } else {
                System.out.println("certificateResponse is empty");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}