⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 cardcertreqservlet.java

📁 一个免费的CA,基于EJB平台的,老师叫我们测试,现把之共享出来让大家参考
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/*************************************************************************
 *                                                                       *
 *  EJBCA: The OpenSource Certificate Authority                          *
 *                                                                       *
 *  This software is free software; you can redistribute it and/or       *
 *  modify it under the terms of the GNU Lesser General Public           *
 *  License as published by the Free Software Foundation; either         *
 *  version 2.1 of the License, or any later version.                    *
 *                                                                       *
 *  See terms of license at gnu.org.                                     *
 *                                                                       *
 *************************************************************************/
 
package org.ejbca.ui.web.pub;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.rmi.RemoteException;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import javax.ejb.CreateException;
import javax.ejb.ObjectNotFoundException;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.ejbca.core.ejb.ca.caadmin.ICAAdminSessionHome;
import org.ejbca.core.ejb.ca.caadmin.ICAAdminSessionRemote;
import org.ejbca.core.ejb.ca.sign.ISignSessionHome;
import org.ejbca.core.ejb.ca.sign.ISignSessionRemote;
import org.ejbca.core.ejb.ca.store.ICertificateStoreSessionHome;
import org.ejbca.core.ejb.ca.store.ICertificateStoreSessionRemote;
import org.ejbca.core.ejb.hardtoken.IHardTokenSessionHome;
import org.ejbca.core.ejb.ra.IUserAdminSessionHome;
import org.ejbca.core.ejb.ra.IUserAdminSessionRemote;
import org.ejbca.core.model.SecConst;
import org.ejbca.core.model.ca.AuthLoginException;
import org.ejbca.core.model.ca.AuthStatusException;
import org.ejbca.core.model.ca.IllegalKeyException;
import org.ejbca.core.model.ca.SignRequestException;
import org.ejbca.core.model.ca.SignRequestSignatureException;
import org.ejbca.core.model.ca.caadmin.CAInfo;
import org.ejbca.core.model.ca.crl.RevokedCertInfo;
import org.ejbca.core.model.hardtoken.profiles.EIDProfile;
import org.ejbca.core.model.hardtoken.profiles.HardTokenProfile;
import org.ejbca.core.model.hardtoken.profiles.SwedishEIDProfile;
import org.ejbca.core.model.log.Admin;
import org.ejbca.core.model.ra.UserDataConstants;
import org.ejbca.core.model.ra.UserDataVO;
import org.ejbca.core.protocol.IResponseMessage;
import org.ejbca.core.protocol.PKCS10RequestMessage;
import org.ejbca.ui.web.RequestHelper;
import org.ejbca.util.Base64;
import org.ejbca.util.CertTools;


/**
 * Servlet used to install a private key with a corresponding certificate in a browser. A new
 * certificate is installed in the browser in following steps:<br>
 * 1. The key pair is generated by the browser. <br>
 * 2. The public part is sent to the servlet in a POST together with user info ("pkcs10|keygen",
 * "inst", "user", "password"). For internet explorer the public key is sent as a PKCS10
 * certificate request. <br>
 * 3. The new certificate is created by calling the RSASignSession session bean. <br>
 * 4. A page containing the new certificate and a script that installs it is returned to the
 * browser. <br>
 * 
 * <p></p>
 * 
 * <p>
 * The following initiation parameters are needed by this servlet: <br>
 * "responseTemplate" file that defines the response to the user (IE). It should have one line
 * with the text "cert =". This line is replaced with the new certificate. "keyStorePass".
 * Password needed to load the key-store. If this parameter is none existing it is assumed that no
 * password is needed. The path could be absolute or relative.<br>
 * </p>
 *
 * @author Original code by Lars Silv閚
 * @version $Id: CardCertReqServlet.java,v 1.13 2007/01/03 14:34:11 anatom Exp $
 */
public class CardCertReqServlet extends HttpServlet {
	private final static Logger log = Logger.getLogger(CardCertReqServlet.class);
    private ISignSessionHome signsessionhome = null;
    private IUserAdminSessionHome useradminhome = null;
    private ICertificateStoreSessionHome certificatestorehome = null;
    private ICAAdminSessionHome caadminsessionhome = null;
    private IHardTokenSessionHome tokenSessionHome = null;

    /**
     * Servlet init
     *
     * @param config servlet configuration
     *
     * @throws ServletException on error
     */
    public void init(ServletConfig config) throws ServletException {
        super.init(config);

        try {
            // Install BouncyCastle provider
            CertTools.installBCProvider();

            // Get EJB context and home interfaces
            InitialContext ctx = new InitialContext();
            signsessionhome = (ISignSessionHome) PortableRemoteObject.narrow(
                      ctx.lookup("RSASignSession"), ISignSessionHome.class );
            useradminhome = (IUserAdminSessionHome) PortableRemoteObject.narrow(
                             ctx.lookup("UserAdminSession"), IUserAdminSessionHome.class );
            certificatestorehome = (ICertificateStoreSessionHome) PortableRemoteObject.narrow(
                    ctx.lookup("CertificateStoreSession"), ICertificateStoreSessionHome.class );
            caadminsessionhome = (ICAAdminSessionHome) javax.rmi.PortableRemoteObject.narrow(ctx.lookup("CAAdminSession"),
                                                                                             ICAAdminSessionHome.class);
            tokenSessionHome = (IHardTokenSessionHome)javax.rmi.PortableRemoteObject.narrow(ctx.lookup("HardTokenSession"),
                                                                                            IHardTokenSessionHome.class);
        } catch( Exception e ) {
            throw new ServletException(e);
        }
    }

    /**
     * Handles HTTP POST
     *
     * @param request servlet request
     * @param response servlet response
     *
     * @throws IOException input/output error
     * @throws ServletException on error
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException {
        final ServletDebug debug = new ServletDebug(request, response);
        boolean usekeyrecovery = false;
        try {
            Admin administrator = new Admin(Admin.TYPE_RA_USER);
            ICertificateStoreSessionRemote certificatestoresession = certificatestorehome.create();
            final String username; {
                Object o = request.getAttribute("javax.servlet.request.X509Certificate");
                final X509Certificate[] certs;
                if ( o!=null && o instanceof X509Certificate[] )
                    certs = (X509Certificate[])o;
                else
                    throw new AuthLoginException("No authenicating certificate");
                RevokedCertInfo rci=certificatestoresession.isRevoked(administrator, certs[0].getIssuerDN().getName(),
                                                                      certs[0].getSerialNumber());
                if ( rci==null || rci.getReason()!=RevokedCertInfo.NOT_REVOKED )
                    throw new UserCertificateRevokedException(certs[0]);
                username = certificatestoresession.findUsernameByCertSerno(administrator,
                        certs[0].getSerialNumber(), certs[0].getIssuerX500Principal().toString());
                if ( username==null || username.length()==0 )
                    throw new ObjectNotFoundException("Not possible to retrieve user name");
            }
            IUserAdminSessionRemote adminsession = useradminhome.create();
            ISignSessionRemote signsession = signsessionhome.create();
            log.debug("Got request for " + username + ".");
            debug.print("<h3>username: " + username + "</h3>");
            
            final UserDataVO data = adminsession.findUser(administrator, username);
            final X509Certificate notRevokedCerts[]; {
                Set set = new HashSet();
                for( Iterator i = certificatestoresession.findCertificatesByUsername(administrator, username).iterator(); i.hasNext(); ) {
                    Object o = i.next();
                    if ( o instanceof X509Certificate ) {
                        X509Certificate cert = (X509Certificate)o;
                        RevokedCertInfo rci=certificatestoresession.isRevoked(administrator, cert.getIssuerDN().getName(), cert.getSerialNumber());
                        if ( rci!=null && rci.getReason()==RevokedCertInfo.NOT_REVOKED )
                            set.add(cert);
                    }
                }
                notRevokedCerts = (X509Certificate[])set.toArray(new X509Certificate[0]);
            }
            if (data == null)
                throw new ObjectNotFoundException();
            
            final String authReq = request.getParameter("authpkcs10");
            final String signReq = request.getParameter("signpkcs10");
            
            if ( authReq!=null && signReq!=null ) {
                final int authCertProfile;
                final int signCertProfile;
                final HardTokenProfile hardTokenProfile = tokenSessionHome.create().getHardTokenProfile(administrator, data.getTokenType());
                {
                    CertProfileID certProfileID = new CertProfileID(certificatestoresession, data, administrator,
                                                                    hardTokenProfile);
                    authCertProfile = certProfileID.getProfileID("authCertProfile", SwedishEIDProfile.CERTUSAGE_AUTHENC);
                    signCertProfile = certProfileID.getProfileID("signCertProfile", SwedishEIDProfile.CERTUSAGE_SIGN);
                }
                final int authCA;
                final int signCA;
                {
                    CAID caid = new CAID(data,administrator, hardTokenProfile);
                    authCA = caid.getProfileID("authCA", SwedishEIDProfile.CERTUSAGE_AUTHENC);
                    signCA = caid.getProfileID("signCA", SwedishEIDProfile.CERTUSAGE_SIGN);
                }
                // if not IE, check if it's manual request
                final byte[] authReqBytes = authReq.getBytes();
                final byte[] signReqBytes = signReq.getBytes();
                if ( authReqBytes!=null && signReqBytes!=null) {
                    try {
                    adminsession.changeUser(administrator, username,data.getPassword(), data.getDN(), data.getSubjectAltName(),
                                            data.getEmail(), true, data.getEndEntityProfileId(), authCertProfile, data.getType(),
                                            SecConst.TOKEN_SOFT_BROWSERGEN, 0, data.getStatus(), authCA);
                    final byte[] authb64cert=pkcs10CertRequest(administrator, signsession, authReqBytes, username, data.getPassword());

                    adminsession.changeUser(administrator, username, data.getPassword(), data.getDN(), data.getSubjectAltName(),
                                            data.getEmail(), true, data.getEndEntityProfileId(), signCertProfile, data.getType(),
                                            SecConst.TOKEN_SOFT_BROWSERGEN, 0, UserDataConstants.STATUS_NEW, signCA);
                    final byte[] signb64cert=pkcs10CertRequest(administrator, signsession, signReqBytes, username, data.getPassword());


                    for (int i=0; i<notRevokedCerts.length; i++)
                        adminsession.revokeCert(administrator, notRevokedCerts[i].getSerialNumber(),
                                                notRevokedCerts[i].getIssuerDN().toString(), username,
                                                RevokedCertInfo.REVOKATION_REASON_SUPERSEDED);

                    sendCertificates(authb64cert, signb64cert, response,  getServletContext(),
                                     getInitParameter("responseTemplate"), notRevokedCerts);
                    } catch( Throwable t ) {
                        if (t instanceof Exception)
                            throw (Exception)t;
                        else
                            throw new Error(t);
                    } finally {
                        data.setStatus(UserDataConstants.STATUS_GENERATED);
                        adminsession.changeUser(administrator, data, true); // set back to original values
                    }
                }
            }
        } catch( UserCertificateRevokedException e) {
            log.error("An error revoking certificaates occured: ", e);
            debug.printMessage(e.getMessage());
            debug.printDebugInfo();
            return;

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -