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

📄 certificatefromrequest.java

📁 一个java开发的非常全面的关于证书发放
💻 JAVA
字号:
/*
  Name:         CertificateFromRequest.java
  Licensing:    LGPL

  API:          Sun (http://java.sun.com) JCE 1.2.2 API (cleanroom implementation by Bouncy Castle)
  Provider:     Bouncy Castle (http://www.bouncycastle.org)

  Disclaimer:

  COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY OF ANY KIND,
  EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED CODE
  IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. THE ENTIRE
  RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED CODE IS WITH YOU. SHOULD ANY COVERED CODE
  PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR)
  ASSUME THE COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY
  CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED
  HEREUNDER EXCEPT UNDER THIS DISCLAIMER.
*/

package net.sourceforge.jcetaglib.taglib.x509;

import net.sourceforge.jcetaglib.lib.CertTools;
import net.sourceforge.jcetaglib.lib.Clean;
import net.sourceforge.jcetaglib.lib.X509Cert;
import org.bouncycastle.jce.PKCS10CertificationRequest;
import org.bouncycastle.jce.netscape.NetscapeCertRequest;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyTagSupport;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.cert.X509Certificate;

/**
 * JSP tag for generating X.509 certificates from PKCS#10 or Netscape requests
 *
 * @jsp.tag
 * name="certificatefromrequest"
 * display-name="CertificateFromRequest"
 * body-content="JSP"
 * example="<jce:certificatefromrequest

 *   	certrequest=\"<%= request.getParameter(\"pkcs10\") %>\"

 *   	subjectdn=\"C=BE, O=NET, OU=Home, CN=Bob, EmailAddress=bob@somewhere.org\"

 *	 	signfile=\"C:/keystores/bob.p12\"

 *	 	signentry=\"ca\"

 *	 	signpassword=\"password\"

 *	 	fingerprint=\"fp\"

 *	 	serialnumber=\"sn\"

 *	 	certificate=\"c\"/>"
 *
 * description="JSP tag for generating X.509 certificates from PKCS#10 or Netscape requests"
 *
 * @author Gert Van Ham
 * @author hamgert@users.sourceforge.net
 * @author http://jcetaglib.sourceforge.net
 * @version $Id: CertificateFromRequest.java,v 1.6 2004/04/15 07:28:36 hamgert Exp $
 */

public class CertificateFromRequest extends BodyTagSupport {
    private static final String PAGE = "page";
    private static final String REQUEST = "request";
    private static final String SESSION = "session";
    private static final String APPLICATION = "application";

    private String signaturealgorithm = "MD5WithRSAEncryption";  // tag attribute

    private String subjectdn;
    private long validity = 365;
    private boolean isca = false;

    private String crldisturi;

    private String netscapeextensions;

    private String signfile;            // tag attribute
    private String signentry;           // tag attribute
    private StringBuffer signpassword;        // tag attribute

    protected String certrequest; // tag attribute
    private String requesttype = "PKCS10"; /* PKCS10 or NS (Netscape/Mozilla)*/

    private int scope = PageContext.PAGE_SCOPE;

    // return certificates...
    // variables
    private String serialnumber;
    private String fingerprint;
    private String certificate;

    public static int getScope(String scope) {
        int ret = PageContext.PAGE_SCOPE; // default

        if (REQUEST.equalsIgnoreCase(scope))
            ret = PageContext.REQUEST_SCOPE;
        else if (SESSION.equalsIgnoreCase(scope))
            ret = PageContext.SESSION_SCOPE;
        else if (APPLICATION.equalsIgnoreCase(scope))
            ret = PageContext.APPLICATION_SCOPE;
        else if (PAGE.equalsIgnoreCase(scope))
            ret = PageContext.PAGE_SCOPE;

        return ret;
    } //getScope()

    public int doEndTag() throws JspException {
        String input;

        // determine the value by...
        if (certrequest != null) {
            // ... reading our attribute
            input = certrequest;
        } else {
            // ... retrieving and trimming our body
            if (bodyContent == null || bodyContent.getString() == null) {
                input = "";
            } else {
                input = bodyContent.getString().trim();
            }
        }

        Security.addProvider(new BouncyCastleProvider());
        PublicKey pubKey;

        try {
            // read CA certificate & private key
            PrivateKey CAprivateKey = X509Cert.getPrivateFromP12(signfile, signentry, signpassword);
            X509Certificate caCert = X509Cert.getCertificateFromP12(signfile, signentry, signpassword);

            // read request
            if (requesttype.equals("PKCS10")) {
                // PKCS10 Request type
                PKCS10CertificationRequest pkcs10 = X509Cert.getPKCS10Request(input);

                if (pkcs10.verify() == false) {
                    throw new JspException("JCE Exception: Unable to generate certificate: Not a valid PKCS10 request");
                }

                pubKey = pkcs10.getPublicKey();

            } else {
                // Netscape request type
                NetscapeCertRequest nscr = X509Cert.getNetscapeRequest(input);

                nscr.setChallenge("challenge");
                if (nscr.verify("challenge") == false) {
                    throw new JspException("JCE Exception: Unable to generate certificate: Not a valid Netscape request");
                }

                pubKey = nscr.getPublicKey();
            }

            // generate certificate
            X509Certificate cert = X509Cert.sign(pubKey
                    , CAprivateKey
                    , caCert
                    , signaturealgorithm
                    , Integer.parseInt(Long.toString(validity))
                    , subjectdn
                    , isca
                    , crldisturi
                    , netscapeextensions);

            // return serialnumber and fingerprint
            pageContext.setAttribute(serialnumber, cert.getSerialNumber().toString(), scope);
            pageContext.setAttribute(fingerprint, CertTools.getFingerprintAsString(cert), scope);

            // Return certificate as string
            byte output[] = cert.getEncoded();
            byte certB64[] = Base64.encode(output);

            pageContext.setAttribute(certificate, "-----BEGIN CERTIFICATE-----\n" + new String(certB64) + "\n-----END CERTIFICATE-----", scope);

        } catch (Exception e) {
            throw new JspException("JCE Exception: Unable to generate certificate: "
                    + e.getMessage(), e);
        }

        return EVAL_PAGE;
    } //doEndTag()

    public void release() {
        // Cleanup all sensitive information
        Clean.blank(signpassword);

        super.release();
    } //release()

    /**
     * @jsp.attribute
     *     description="Optional attribute, the certificate request. The body of the tag will be taken if omitted."
     *     type="java.lang.String"
     *     required="false"
     *     rtexprvalue="true"
     */
    public void setCertrequest(String certrequest) {
        this.certrequest = certrequest;
    }

    public String getCertrequest() {
        return certrequest;
    }

    /**
     * @jsp.attribute
     *     description="The request type. 'PKCS10' for PKCS#10 type request, 'NS' for Netscape type requests. Default is 'PKCS10'"
     *     type="java.lang.String"
     *     required="false"
     *     rtexprvalue="true"
     */
    public void setRequesttype(String requesttype) {
        this.requesttype = requesttype;
    }

    /**
     * @jsp.attribute
     *     description="Signature algorithm. Default is 'MD5WithRSAEncryption'"
     *     type="java.lang.String"
     *     required="false"
     *     rtexprvalue="true"
     */
    public void setSignaturealgorithm(String signaturealgorithm) {
        this.signaturealgorithm = signaturealgorithm;
    }

    /**
     * @jsp.attribute
     *     description="The subject DN string. e.g. 'C=BE, O=NET, OU=Sourceforge, CN=CertAuthority, E=info@certauthority.org' Important: if you want to use the certificate for SSL server purposes you must specify the full server & domain name as the 'CN' entry (e.g. '... CN=www.oracle.com ...')"
     *     type="java.lang.String"
     *     required="true"
     *     rtexprvalue="true"
     */
    public void setSubjectdn(String subjectdn) {
        this.subjectdn = subjectdn;
    }

    /**
     * @jsp.attribute
     *     description="The validity of the certificate in days. Default is 365"
     *     type="java.lang.Long"
     *     required="false"
     *     rtexprvalue="true"
     */
    public void setValidity(long validity) {
        this.validity = validity;
    }

    /**
     * @jsp.attribute
     *     description="Defines this certificate as a CA (Certificate Authority). Default is false. If you want to use this certificate as intermediate certificate, you have to set this parameter to true"
     *     type="java.lang.Boolean"
     *     required="false"
     *     rtexprvalue="true"
     */
    public void setIsca(boolean isca) {
        this.isca = isca;
    }

    /**
     * @jsp.attribute
     *     description="CRL (Certificate Revocation List) distribution URI extension. Default is none"
     *     type="java.lang.String"
     *     required="false"
     *     rtexprvalue="true"
     */
    public void setCrldisturi(String crldisturi) {
        this.crldisturi = crldisturi;
    }

    /**
     * @jsp.attribute
     *     description="Adds Netscape certificate extensions to the certificate. If this certificate must work with Netscape products (or Mozilla), you have to specify one of the following parameters:&#10&#10
     *      'CA': this certificate can be used as SSL Certificate Authority, Email Signer and Object Signer&#10
     *      'SERVER': this certificate can be used as SSL Server.&#10
     *      'CLIENT': this certificate can be used as SSL Client, Email Recipient and Object Signer&#10
     *      'ALL': this certificate can be used for all above purposes."
     *     type="java.lang.String"
     *     required="false"
     *     rtexprvalue="true"
     */
    public void setNetscapeextensions(String netscapeextensions) {
        this.netscapeextensions = netscapeextensions;
    }

    /**
     * @jsp.attribute
     *     description="The PKCS#12 (P12) keystore where the CA signing certificate is stored"
     *     type="java.lang.String"
     *     required="true"
     *     rtexprvalue="true"
     */
    public void setSignfile(String signfile) {
        this.signfile = signfile;
    }

    /**
     * @jsp.attribute
     *     description="The PKCS#12 (P12) keystore entry name for the CA signing certificate"
     *     type="java.lang.String"
     *     required="true"
     *     rtexprvalue="true"
     */
    public void setSignentry(String signentry) {
        this.signentry = signentry;
    }

    /**
     * @jsp.attribute
     *     description="The PKCS#12 (P12) keystore signing password"
     *     type="java.lang.StringBuffer"
     *     required="true"
     *     rtexprvalue="true"
     */
    public void setSignpassword(StringBuffer signpassword) {
        this.signpassword = signpassword;
    }

    /**
     * @jsp.attribute
     *     description="Scope of the return variables. Can be 'page', 'session', 'request' or 'application'. Default is 'page'"
     *     type="java.lang.String"
     *     required="false"
     *     rtexprvalue="false"
     */
    public void setScope(String scope) {
        this.scope = getScope(scope);
    }

    /**
     * @jsp.attribute
     *     description="Variable to store the certificate serial number"
     *     type="java.lang.String"
     *     required="true"
     *     rtexprvalue="true"
     */
    public void setSerialnumber(String serialnumber) {
        this.serialnumber = serialnumber;
    }

    public String getSerialnumber() {
        return serialnumber;
    }

    /**
     * @jsp.attribute
     *     description="Variable to store the certificate fingerprint (SHA-1)"
     *     type="java.lang.String"
     *     required="true"
     *     rtexprvalue="true"
     */
    public void setFingerprint(String fingerprint) {
        this.fingerprint = fingerprint;
    }

    public String getFingerprint() {
        return fingerprint;
    }

    /**
     * @jsp.attribute
     *     description="Variable to store the certificate as a PEM formatted string"
     *     type="java.lang.String"
     *     required="true"
     *     rtexprvalue="true"
     */
    public void setCertificate(String certificate) {
        this.certificate = certificate;
    }

    public String getCertificate() {
        return certificate;
    }
}

⌨️ 快捷键说明

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