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

📄 cardcertreqservlet.java

📁 一个免费的CA,基于EJB平台的,老师叫我们测试,现把之共享出来让大家参考
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
        } catch (ObjectNotFoundException oe) {
            log.error("Non existent username!", oe);
            debug.printMessage("Non existent username!");
            debug.printDebugInfo();
            return;
        } catch (AuthStatusException ase) {
            log.error("Wrong user status!", ase);
            debug.printMessage("Wrong user status!");
            if (usekeyrecovery) {
                debug.printMessage(
                "To generate a certificate for a user the user must have status new, failed or inprocess.");
            } else {
                debug.printMessage(
                "To generate a certificate for a user the user must have status new, failed or inprocess.");
            }
            debug.printDebugInfo();
            return;
        } catch (AuthLoginException ale) {
            log.error("Wrong password for user!", ale);
            debug.printMessage("Wrong username or password!");
            debug.printDebugInfo();
            return;
        } catch (SignRequestException re) {
            log.error("Invalid request!", re);
            debug.printMessage("Invalid request!");
            debug.printMessage("Please supply a correct request.");
            debug.printDebugInfo();
            return;
        } catch (SignRequestSignatureException se) {
            log.error("Invalid signature on certificate request!", se);
            debug.printMessage("Invalid signature on certificate request!");
            debug.printMessage("Please supply a correctly signed request.");
            debug.printDebugInfo();
            return;
        } catch (java.lang.ArrayIndexOutOfBoundsException ae) {
            log.error("Empty or invalid request received.", ae);
            debug.printMessage("Empty or invalid request!");
            debug.printMessage("Please supply a correct request.");
            debug.printDebugInfo();
            return;
        } catch (IllegalKeyException e) {
            log.error("Illegal Key received: ", e);
            debug.printMessage("Invalid Key in request: "+e.getMessage());
            debug.printMessage("Please supply a correct request.");
            debug.printDebugInfo();
            return;
        } catch (Exception e) {
            log.error("Exception occured: ", e);
            debug.print("<h3>parameter name and values: </h3>");
            Enumeration paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String name = paramNames.nextElement().toString();
                String parameter = request.getParameter(name);
                debug.print("<h4>" + name + ":</h4>" + parameter + "<br>");
            }
            debug.takeCareOfException(e);
            debug.printDebugInfo();
        }
    } //doPost

    private class UserCertificateRevokedException extends Exception {
        UserCertificateRevokedException(X509Certificate cert) {
            super("User certificate with serial number "+cert.getSerialNumber() +
                  " from issuer \'"+cert.getIssuerX500Principal()+"\' is revoked.");
        }
    }
    private class CAID extends BaseID {
        final private ICAAdminSessionRemote caadminsession;
        CAID(UserDataVO d, Admin a, HardTokenProfile hardTokenProfile) throws RemoteException, CreateException {
            super(d, a, hardTokenProfile);
            caadminsession = caadminsessionhome.create();                       
        }
        protected int getFromName(String name) throws RemoteException {
            CAInfo caInfo = caadminsession.getCAInfo(administrator, name);
            if ( caInfo!=null )
                return caInfo.getCAId();
            else
                return 0;
        }
        protected int getFromOldData() {
            return data.getCAId();
        }
        protected int getFromHardToken(int keyType) {
            final int id = hardTokenProfile.getCAId(keyType);
            if ( id!=EIDProfile.CAID_USEUSERDEFINED )
                return id;
            else
                return data.getCAId();
        }
    }
    private class CertProfileID extends BaseID {
        final ICertificateStoreSessionRemote certificatestoresession;
        CertProfileID(ICertificateStoreSessionRemote c, UserDataVO d, Admin a,
                      HardTokenProfile hardTokenProfile) throws RemoteException, CreateException {
            super(d, a, hardTokenProfile);
            certificatestoresession = c;
        }
        protected int getFromName(String name) throws RemoteException {
            return certificatestoresession.getCertificateProfileId(administrator, name);
        }
        protected int getFromOldData() {
            return data.getCertificateProfileId();
        }
        protected int getFromHardToken(int keyType) {
            return hardTokenProfile.getCertificateProfileId(keyType);
        }
    }
    private abstract class BaseID {
        final UserDataVO data;
        final Admin administrator;
        final EIDProfile hardTokenProfile;
        
        protected abstract int getFromHardToken(int keyType);
        protected abstract int getFromName(String name) throws RemoteException;
        protected abstract int getFromOldData();
        BaseID(UserDataVO d, Admin a, HardTokenProfile htp) {
            data = d;
            administrator = a;
            if ( htp!=null && htp instanceof EIDProfile )
                hardTokenProfile = (EIDProfile)htp;
            else
                hardTokenProfile = null;
        }
        public int getProfileID(String parameterName, int keyType) throws RemoteException {
            if ( hardTokenProfile!=null )
                return getFromHardToken(keyType);
            String name = CardCertReqServlet.this.getInitParameter(parameterName);
            if ( name!=null && name.length()>0 ) {
                final int id = getFromName(name);
                log.debug("parameter name "+parameterName+" has ID "+id);
                if (id!=0)
                    return id;
            }
            return getFromOldData();
        }
    }
    /**
     * Handles HTTP GET
     *
     * @param request servlet request
     * @param response servlet response
     *
     * @throws IOException input/output error
     * @throws ServletException on error
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
        log.debug(">doGet()");
        response.setHeader("Allow", "POST");

        ServletDebug debug = new ServletDebug(request, response);
        debug.print("The certificate request servlet only handles POST method.");
        debug.printDebugInfo();
        log.debug("<doGet()");
    }

    // doGet
    
    
    /**
     * Reads template and inserts cert to send back to netid for installation of cert
     *
     * @param b64cert cert to be installed in netid
     * @param response utput stream to send to
     * @param sc serveltcontext
     * @param responseTemplate path to responseTemplate
     * @param notRevokedCerts 
     * @param classid replace
     *
     * @throws Exception on error
     */
    private static void sendCertificates(byte[] authb64cert,byte[] signb64cert, HttpServletResponse response, ServletContext sc,
        String responseTemplate, X509Certificate[] notRevokedCerts) throws Exception {
        if (authb64cert.length == 0 || signb64cert.length == 0) {
            log.error("0 length certificate can not be sent to  client!");
            return;
        }
        StringWriter sw = new StringWriter();
        {
            BufferedReader br = new BufferedReader(new InputStreamReader(sc.getResourceAsStream(responseTemplate)));
            PrintWriter pw = new PrintWriter(sw);
            while (true) {
                String line = br.readLine();
                if (line == null)
                    break;
                line = line.replaceAll("TAG_authb64cert",new String(authb64cert));
                line = line.replaceAll("TAG_signb64cert",new String(signb64cert));
                if ( notRevokedCerts.length > 0 )
                    line = line.replaceAll("TAG_certToRemove1",new String(Base64.encode(notRevokedCerts[0].getEncoded(),false)));
                if ( notRevokedCerts.length > 1 )
                    line = line.replaceAll("TAG_certToRemove2",new String(Base64.encode(notRevokedCerts[1].getEncoded(),false)));
                if ( notRevokedCerts.length > 2 )
                    line = line.replaceAll("TAG_certToRemove3",new String(Base64.encode(notRevokedCerts[2].getEncoded(),false)));
                if ( notRevokedCerts.length > 3 )
                    line = line.replaceAll("TAG_certToRemove4",new String(Base64.encode(notRevokedCerts[3].getEncoded(),false)));
                pw.println(line);
            }
            pw.close();
            sw.flush();
        }
        {
            OutputStream out = response.getOutputStream();
            PrintWriter pw = new PrintWriter(out);
            log.debug(sw);
            pw.print(sw);
            pw.close();
            out.flush();
        }
    } // sendCertificates
    
    /**
     * Handles PKCS10 certificate request, these are constructed as: <code> CertificationRequest
     * ::= SEQUENCE { certificationRequestInfo  CertificationRequestInfo, signatureAlgorithm
     * AlgorithmIdentifier{{ SignatureAlgorithms }}, signature                       BIT STRING }
     * CertificationRequestInfo ::= SEQUENCE { version             INTEGER { v1(0) } (v1,...),
     * subject             Name, subjectPKInfo   SubjectPublicKeyInfo{{ PKInfoAlgorithms }},
     * attributes          [0] Attributes{{ CRIAttributes }}} SubjectPublicKeyInfo { ALGORITHM :
     * IOSet} ::= SEQUENCE { algorithm           AlgorithmIdentifier {{IOSet}}, subjectPublicKey
     * BIT STRING }</code> PublicKey's encoded-format has to be RSA X.509.
     *
     * @param signsession signsession to get certificate from
     * @param b64Encoded base64 encoded pkcs10 request message
     * @param username username of requesting user
     * @param password password of requesting user
     * @param resulttype should indicate if a PKCS7 or just the certificate is wanted.
     *
     * @return Base64 encoded byte[] 
     */
    private byte[] pkcs10CertRequest(Admin administrator, ISignSessionRemote signsession, byte[] b64Encoded,
        String username, String password) throws Exception {
        byte[] result = null;	
        X509Certificate cert=null;
		PKCS10RequestMessage req = RequestHelper.genPKCS10RequestMessageFromPEM(b64Encoded);
		req.setUsername(username);
        req.setPassword(password);
        IResponseMessage resp = signsession.createCertificate(administrator,req,Class.forName("org.ejbca.core.protocol.X509ResponseMessage"));
        cert = CertTools.getCertfromByteArray(resp.getResponseMessage());
          result = cert.getEncoded();

        return Base64.encode(result, false);
    } //pkcs10CertReq
}


// CertReqServlet

⌨️ 快捷键说明

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