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

📄 encryptwithcert.java

📁 一个java开发的非常全面的关于证书发放
💻 JAVA
字号:
/*
  Name:         EncryptWithCert.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.crypto;

import net.sourceforge.jcetaglib.lib.Asymmetric;
import net.sourceforge.jcetaglib.lib.CertTools;
import net.sourceforge.jcetaglib.lib.Clean;
import net.sourceforge.jcetaglib.lib.X509Cert;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyTagSupport;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.X509Certificate;

/**
 * JSP tag used for encryption/decryption of strings with public/private keys
 * (X.509 certificates)
 *
 * @jsp.tag
 * name="encryptwithcert"
 * display-name="EncryptWithCert"
 * body-content="JSP"
 * example="
 *		<%-- Encrypts tag body with certificate and store it in session variable 'myvar' --%>

 *		<jce:encryptwithcert

 *			storefile=\"c:/keystore/mystore.p12\"

 *			storeentry=\"otheruser\"

 *			storepassword=\"<%= new StringBuffer(\"password\") %>\"

 *			var=\"myvar\"

 *			scope=\"session\">

 *		Please encrypt this string...

 *		</jce:encrypt>"
 *
 * description="JSP tag used for encryption/decryption of strings with public/private keys (X.509 certificates)"
 *
 * @author Gert Van Ham
 * @author hamgert@users.sourceforge.net
 * @author http://jcetaglib.sourceforge.net
 * @version $Id: EncryptWithCert.java,v 1.5 2004/04/15 07:28:35 hamgert Exp $
 */
public class EncryptWithCert 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 static final String ENCRYPT = "encrypt";

    private StringBuffer value; // tag attribute
    private String var;     // tag attribute
    private int scope = PageContext.PAGE_SCOPE;      // tag attribute

    /* Attributes for X.509 keystore */

    // P12 keystore...
    private String storefile;            // tag attribute
    private String storeentry;           // tag attribute
    private StringBuffer storepassword;        // tag attribute

    // ... OR PEM string
    private String pemstring;            // tag attribute

    // ... OR PEM file
    private String pemfile;              // tag attribute

    private String action = "ENCRYPT";  // tag attribute

    private StringBuffer input;    // what we'll store in scope:var
    private StringBuffer output;   // return text

    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 {

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

        // Encrypt or decrypt
        try {
            if (ENCRYPT.equalsIgnoreCase(action)) {
                X509Certificate cert = null;
                PublicKey encryptKey;

                try {
                    // Retrieve the private key (for signing) from one of the three possible keystores
                    if (storefile == null || storefile == "") {
                        if (pemfile == null || pemfile == "") {
                            // use PEM string
                            InputStream pemstream = new ByteArrayInputStream(pemstring.getBytes());
                            cert = CertTools.getCertfromPEM(pemstream);
                        } else {
                            // use PEM store
                            cert = CertTools.getCertfromPEM(pemfile);
                        }
                    } else {
                        // use PKCS #12 keystore
                        cert = X509Cert.getCertificateFromP12(storefile, storeentry, storepassword);
                    }
                } catch (Exception e) {
                    throw new JspException("JCE Exception - keystore could not be loaded: " + e.getMessage(), e);
                }

                // get the public key from the certificate
                encryptKey = cert.getPublicKey();

                output = Asymmetric.encrypt(input, encryptKey);

            } else {
                PrivateKey decryptKey;

                try {
                    // Retrieve the private key (for signing) from one of the three possible keystores
                    if (storefile == null || storefile == "") {
                        if (pemfile == null || pemfile == "") {
                            // use PEM string
                            InputStream pemstream = new ByteArrayInputStream(pemstring.getBytes());
                            decryptKey = CertTools.getPrivatefromPEM(pemstream, "");
                        } else {
                            // use PEM store
                            decryptKey = CertTools.getPrivatefromPEM(pemfile, "");
                        }
                    } else {
                        // use PKCS #12 keystore
                        decryptKey = X509Cert.getPrivateFromP12(storefile, storeentry, storepassword);
                    }
                } catch (Exception e) {
                    throw new JspException("JCE Exception - keystore could not be loaded: " + e.getMessage(), e);
                }

                output = Asymmetric.decrypt(input, decryptKey);
            }
        } catch (Exception e) {
            throw new JspException("JCE Exception: " + e.getMessage(), e);
        }

        // decide what to do with the result
        if (var != null) {
            if (output != null) {
                pageContext.setAttribute(var, output, scope);
            }
        } else {
            if (bodyContent != null) {
                bodyContent.clearBody();
            }

            try {
                JspWriter w = pageContext.getOut();
                w.print(output);
            } catch (IOException ex) {
                throw new JspException(ex.getMessage(), ex);
            }
        }

        return EVAL_PAGE;
    } // doEndTag()

    public void release() {
        // Cleanup all sensitive information
        Clean.blank(value);
        Clean.blank(storepassword);
        Clean.blank(input);
        Clean.blank(output);

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

    /**
     * @jsp.attribute
     *     description="Optional attribute, the string to encrypt or decrypt. The body of the tag will be taken if omitted"
     *     type="java.lang.StringBuffer"
     *     required="false"
     *     rtexprvalue="true"
     */
    public void setValue(StringBuffer value) {
        this.value = value;
    }

    public StringBuffer getValue() {
        return value;
    }

    /**
     * @jsp.attribute
     *     description="Optional attribute, variable to store the encrypted string. The string will be printed if omitted"
     *     type="java.lang.String"
     *     required="false"
     *     rtexprvalue="false"
     */
    public void setVar(String var) {
        this.var = var;
    }

    public String getVar() {
        return var;
    }

    /**
     * @jsp.attribute
     *     description="Scope of the 'var' attribute. 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="The PKCS#12 (P12) keystore where the private key is stored"
     *     type="java.lang.String"
     *     required="true"
     *     rtexprvalue="true"
     */
    public void setStorefile(String storefile) {
        this.storefile = storefile;
    }

    /**
     * @jsp.attribute
     *     description="The PKCS#12 (P12) keystore entry name for private key"
     *     type="java.lang.String"
     *     required="true"
     *     rtexprvalue="true"
     */
    public void setStoreentry(String storeentry) {
        this.storeentry = storeentry;
    }

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

    /**
     * @jsp.attribute
     *     description="The receiver's certificate/public key (if action=encrypt) stored in a PEM file OR The receiver's private key (if action=decrypt) stored in a PEM file "
     *     type="java.lang.String"
     *     required="false"
     *     rtexprvalue="true"
     */
    public void setPemfile(String pemfile) {
        this.pemfile = pemfile;
    }

    /**
     * @jsp.attribute
     *     description="The receiver's certificate/public key (if action=encrypt) as a PEM formatted string OR The receiver's private key (if action=decrypt) as a PEM formatted string"
     *     type="java.lang.String"
     *     required="false"
     *     rtexprvalue="true"
     */
    public void setPemstring(String pemstring) {
        this.pemstring = pemstring;
    }

    /**
     * @jsp.attribute
     *     description="The action to perform. 'encrypt' for encryption, 'decrypt' for decryption. Default is 'encrypt'"
     *     type="java.lang.String"
     *     required="false"
     *     rtexprvalue="false"
     */
    public void setAction(String action) {
        this.action = action;
    }
}

⌨️ 快捷键说明

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