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

📄 certreqservlet.java

📁 用来生成java证书
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
            debug.printMessage(                "To generate a certificate a valid username and password must be entered.");            debug.printDebugInfo();            return;        } catch (SignRequestException re) {            log.debug("Invalid request!");            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 (ArrayIndexOutOfBoundsException ae) {            log.debug("Empty or invalid request received.");            debug.printMessage("Empty or invalid request!");            debug.printMessage("Please supply a correct request.");            debug.printDebugInfo();            return;        } catch (org.ejbca.core.model.ca.IllegalKeyException e) {            log.debug("Illegal Key received: "+e.getMessage());            debug.printMessage("Invalid Key in request: "+e.getMessage());            debug.printMessage("Please supply a correct request.");            debug.printDebugInfo();            return;        } catch (Exception e) {        	Throwable e1 = e.getCause();        	if (e1 instanceof CATokenOfflineException) {	            // this is already logged as an error, so no need to log it one more time	            debug.printMessage("CA token is off line: "+e1.getMessage());	            debug.printMessage("Contact your administrator.");	            debug.printDebugInfo();	            return;							} else {	            log.debug("Unknown error occured: ", e);	            debug.print("Parameter name and values:\n");	            Enumeration paramNames = request.getParameterNames();	            while (paramNames.hasMoreElements()) {	                String name = paramNames.nextElement().toString();	                String parameter = request.getParameter(name);	                if (!StringUtils.equals(name, "password")) {	                    debug.print(name + ": '" + parameter + "'\n");                		                } else {	                	debug.print(name + ": <hidden>\n");	                }	            }	            debug.takeCareOfException(e);	            debug.printDebugInfo();			}        }    }    //doPost    /**     * 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    /**     * method to create an install package for OpenVPN including keys and send to user.     * Contributed by: Jon Bendtsen, jon.bendtsen(at)laerdal.dk     */    private void sendOpenVPNToken(KeyStore ks, String username, String kspassword, HttpServletResponse out) throws Exception {    	ByteArrayOutputStream buffer = new ByteArrayOutputStream();    	ks.store(buffer, kspassword.toCharArray());    	    	File fout = new File("/usr/local/tmp/" + username + ".p12");    	FileOutputStream certfile = new FileOutputStream(fout);    	    	Enumeration en = ks.aliases();    	String alias = (String)en.nextElement();    	// Then get the certificates    	Certificate[] certs = KeyTools.getCertChain(ks, alias);    	// The first  one (certs[0]) is the users cert and the last    	// one (certs [certs.lenght-1]) is the CA-cert    	X509Certificate x509cert = (X509Certificate) certs[0];    	String IssuerDN = x509cert.getIssuerDN().toString();    	String SubjectDN = x509cert.getSubjectDN().toString();    	    	// export the users certificate to file    	buffer.writeTo(certfile);    	buffer.flush();    	buffer.close();    	certfile.close();    	    	// run shell script, which will also remove the created files    	// parameters are the username, IssuerDN and SubjectDN    	// IssuerDN and SubjectDN will be used to select the right    	// openvpn configuration file    	// they have to be written to stdin of the script to support    	// spaces in the username, IssuerDN or SubjectDN    	Runtime rt = Runtime.getRuntime();    	if (rt==null) {    		log.error("getRuntime failed. null pointer");    	} else {    		Process p = rt.exec("/usr/local/ejbca/bin/mk_openvpn_" + "windows_installer.sh");    		if (p==null) {    			log.error("execution of openvpn windows" + " installer script failed. Null pointer");    		} else {    			OutputStream pstdin = p.getOutputStream();    			PrintStream stdoutp = new PrintStream(pstdin);    			stdoutp.println(username);    			stdoutp.println(IssuerDN);    			stdoutp.println(SubjectDN);    			stdoutp.flush();    			stdoutp.close();    			pstdin.close();    			int exitVal = p.waitFor();    			if (exitVal != 0) {        			log.error("Openvpn windows installer script exitValue: " + exitVal);    				    			} else {        			log.debug("Openvpn windows installer script exitValue: " + exitVal);    				    			}    		}    	}    	    	// we ought to check if the script was okay or not, but in a little    	// while we will look for the openvpn-gui-install-$username.exe    	// and fail there if the script failed. Also, one could question    	// what to do if it did fail, serve the user the certificate?    	    	// sending the OpenVPN windows installer    	String filename = "openvpn-gui-install-" + username + ".exe";    	File fin =  new File("/usr/local/tmp/" + filename);    	FileInputStream vpnfile = new FileInputStream(fin);    	    	out.setContentType("application/x-msdos-program");    	out.setHeader("Content-disposition", "filename=" + filename);		out.setContentLength( new Long(fin.length()).intValue() );		OutputStream os = out.getOutputStream();     	byte[] buf = new byte[4096];    	int offset = 0;    	int bytes = 0;    	while ( (bytes=vpnfile.read(buf)) != -1 ) {    		os.write(buf,0,bytes);    		offset += bytes;    	}    	vpnfile.close();    	// delete OpenVPN windows installer, the script will delete cert.    	fin.delete();    	out.flushBuffer();    	    } // sendOpenVPNToken        private void sendP12Token(KeyStore ks, String username, String kspassword,        HttpServletResponse out) throws Exception {        ByteArrayOutputStream buffer = new ByteArrayOutputStream();        ks.store(buffer, kspassword.toCharArray());        out.setContentType("application/x-pkcs12");        out.setHeader("Content-disposition", "filename=" + username + ".p12");        out.setContentLength(buffer.size());        buffer.writeTo(out.getOutputStream());        out.flushBuffer();        buffer.close();    }    private void sendJKSToken(KeyStore ks, String username, String kspassword,        HttpServletResponse out) throws Exception {        ByteArrayOutputStream buffer = new ByteArrayOutputStream();        ks.store(buffer, kspassword.toCharArray());        out.setContentType("application/octet-stream");        out.setHeader("Content-disposition", "filename=" + username + ".jks");        out.setContentLength(buffer.size());        buffer.writeTo(out.getOutputStream());        out.flushBuffer();        buffer.close();    }    private void sendPEMTokens(KeyStore ks, String username, String kspassword,        HttpServletResponse out) throws Exception {        ByteArrayOutputStream buffer = new ByteArrayOutputStream();        String alias = "";        // Find the key private key entry in the keystore        Enumeration e = ks.aliases();        Object o = null;        PrivateKey serverPrivKey = null;        while (e.hasMoreElements()) {            o = e.nextElement();            if (o instanceof String) {                if ((ks.isKeyEntry((String) o)) &&                        ((serverPrivKey = (PrivateKey) ks.getKey((String) o,                                kspassword.toCharArray())) != null)) {                    alias = (String) o;                    break;                }            }        }        byte[] privKeyEncoded = "".getBytes();        if (serverPrivKey != null) {            privKeyEncoded = serverPrivKey.getEncoded();        }        //Certificate chain[] = ks.getCertificateChain((String) o);        Certificate[] chain = KeyTools.getCertChain(ks, (String) o);        X509Certificate userX509Certificate = (X509Certificate) chain[0];        byte[] output = userX509Certificate.getEncoded();        String sn = CertTools.getSubjectDN(userX509Certificate);        String subjectdnpem = sn.replace(',', '/');        String issuerdnpem = CertTools.getIssuerDN(userX509Certificate).replace(',', '/');        buffer.write(bagattributes);        buffer.write(friendlyname);        buffer.write(alias.getBytes());        buffer.write(NL);        buffer.write(beginPrivateKey);        buffer.write(NL);        byte[] privKey = Base64.encode(privKeyEncoded);        buffer.write(privKey);        buffer.write(NL);        buffer.write(endPrivateKey);        buffer.write(NL);        buffer.write(bagattributes);        buffer.write(friendlyname);        buffer.write(alias.getBytes());        buffer.write(NL);        buffer.write(subject);        buffer.write(subjectdnpem.getBytes());        buffer.write(NL);        buffer.write(issuer);        buffer.write(issuerdnpem.getBytes());        buffer.write(NL);        buffer.write(beginCertificate);        buffer.write(NL);        byte[] userCertB64 = Base64.encode(output);        buffer.write(userCertB64);        buffer.write(NL);        buffer.write(endCertificate);        buffer.write(NL);        if (CertTools.isSelfSigned(userX509Certificate)) {        } else {            for (int num = 1; num < chain.length; num++) {                X509Certificate tmpX509Cert = (X509Certificate) chain[num];                sn = CertTools.getSubjectDN(tmpX509Cert);                String cn = CertTools.getPartFromDN(sn, "CN");                if (StringUtils.isEmpty(cn)) {                	cn="Unknown";                }                subjectdnpem = sn.replace(',', '/');                issuerdnpem = CertTools.getIssuerDN(tmpX509Cert).replace(',', '/');                buffer.write(bagattributes);                buffer.write(friendlyname);                buffer.write(cn.getBytes());                buffer.write(NL);                buffer.write(subject);                buffer.write(subjectdnpem.getBytes());                buffer.write(NL);                buffer.write(issuer);                buffer.write(issuerdnpem.getBytes());                buffer.write(NL);                byte[] tmpOutput = tmpX509Cert.getEncoded();                buffer.write(beginCertificate);                buffer.write(NL);                byte[] tmpCACertB64 = Base64.encode(tmpOutput);                buffer.write(tmpCACertB64);                buffer.write(NL);                buffer.write(endCertificate);                buffer.write(NL);            }        }        out.setContentType("application/octet-stream");        out.setHeader("Content-disposition", " attachment; filename=" + username + ".pem");        buffer.writeTo(out.getOutputStream());        out.flushBuffer();        buffer.close();    }}// CertReqServlet

⌨️ 快捷键说明

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