KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sourceforge > jcetaglib > taglib > crypto > EncryptWithCert


1 /*
2   Name: EncryptWithCert.java
3   Licensing: LGPL
4
5   API: Sun (http://java.sun.com) JCE 1.2.2 API (cleanroom implementation by Bouncy Castle)
6   Provider: Bouncy Castle (http://www.bouncycastle.org)
7
8   Disclaimer:
9
10   COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY OF ANY KIND,
11   EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED CODE
12   IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. THE ENTIRE
13   RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED CODE IS WITH YOU. SHOULD ANY COVERED CODE
14   PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR)
15   ASSUME THE COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY
16   CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED
17   HEREUNDER EXCEPT UNDER THIS DISCLAIMER.
18 */

19
20 package net.sourceforge.jcetaglib.taglib.crypto;
21
22 import net.sourceforge.jcetaglib.lib.Asymmetric;
23 import net.sourceforge.jcetaglib.lib.CertTools;
24 import net.sourceforge.jcetaglib.lib.Clean;
25 import net.sourceforge.jcetaglib.lib.X509Cert;
26
27 import javax.servlet.jsp.JspException JavaDoc;
28 import javax.servlet.jsp.JspWriter JavaDoc;
29 import javax.servlet.jsp.PageContext JavaDoc;
30 import javax.servlet.jsp.tagext.BodyTagSupport JavaDoc;
31 import java.io.ByteArrayInputStream JavaDoc;
32 import java.io.IOException JavaDoc;
33 import java.io.InputStream JavaDoc;
34 import java.security.PrivateKey JavaDoc;
35 import java.security.PublicKey JavaDoc;
36 import java.security.cert.X509Certificate JavaDoc;
37
38 /**
39  * JSP tag used for encryption/decryption of strings with public/private keys
40  * (X.509 certificates)
41  *
42  * @jsp.tag
43  * name="encryptwithcert"
44  * display-name="EncryptWithCert"
45  * body-content="JSP"
46  * example="
47  * <%-- Encrypts tag body with certificate and store it in session variable 'myvar' --%>

48  * <jce:encryptwithcert

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

50  * 	storeentry=\"otheruser\"

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

52  * 	var=\"myvar\"

53  * 	scope=\"session\">

54  * Please encrypt this string...

55  * </jce:encrypt>"
56  *
57  * description="JSP tag used for encryption/decryption of strings with public/private keys (X.509 certificates)"
58  *
59  * @author Gert Van Ham
60  * @author hamgert@users.sourceforge.net
61  * @author http://jcetaglib.sourceforge.net
62  * @version $Id: EncryptWithCert.java,v 1.5 2004/04/15 07:28:35 hamgert Exp $
63  */

64 public class EncryptWithCert extends BodyTagSupport JavaDoc {
65
66     private static final String JavaDoc PAGE = "page";
67     private static final String JavaDoc REQUEST = "request";
68     private static final String JavaDoc SESSION = "session";
69     private static final String JavaDoc APPLICATION = "application";
70
71     private static final String JavaDoc ENCRYPT = "encrypt";
72
73     private StringBuffer JavaDoc value; // tag attribute
74
private String JavaDoc var; // tag attribute
75
private int scope = PageContext.PAGE_SCOPE; // tag attribute
76

77     /* Attributes for X.509 keystore */
78
79     // P12 keystore...
80
private String JavaDoc storefile; // tag attribute
81
private String JavaDoc storeentry; // tag attribute
82
private StringBuffer JavaDoc storepassword; // tag attribute
83

84     // ... OR PEM string
85
private String JavaDoc pemstring; // tag attribute
86

87     // ... OR PEM file
88
private String JavaDoc pemfile; // tag attribute
89

90     private String JavaDoc action = "ENCRYPT"; // tag attribute
91

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

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

98         if (REQUEST.equalsIgnoreCase(scope))
99             ret = PageContext.REQUEST_SCOPE;
100         else if (SESSION.equalsIgnoreCase(scope))
101             ret = PageContext.SESSION_SCOPE;
102         else if (APPLICATION.equalsIgnoreCase(scope))
103             ret = PageContext.APPLICATION_SCOPE;
104         else if (PAGE.equalsIgnoreCase(scope))
105             ret = PageContext.PAGE_SCOPE;
106
107         return ret;
108     } //getScope()
109

110     public int doEndTag() throws JspException JavaDoc {
111
112         // determine the value by...
113
if (value != null) {
114             // ... reading our attribute
115
input = value;
116         } else {
117             // ... retrieving and trimming our body
118
if (bodyContent == null || bodyContent.getString() == null) {
119                 input = new StringBuffer JavaDoc("");
120             } else {
121                 input = new StringBuffer JavaDoc(bodyContent.getString().trim());
122             }
123         }
124
125         // Encrypt or decrypt
126
try {
127             if (ENCRYPT.equalsIgnoreCase(action)) {
128                 X509Certificate JavaDoc cert = null;
129                 PublicKey JavaDoc encryptKey;
130
131                 try {
132                     // Retrieve the private key (for signing) from one of the three possible keystores
133
if (storefile == null || storefile == "") {
134                         if (pemfile == null || pemfile == "") {
135                             // use PEM string
136
InputStream JavaDoc pemstream = new ByteArrayInputStream JavaDoc(pemstring.getBytes());
137                             cert = CertTools.getCertfromPEM(pemstream);
138                         } else {
139                             // use PEM store
140
cert = CertTools.getCertfromPEM(pemfile);
141                         }
142                     } else {
143                         // use PKCS #12 keystore
144
cert = X509Cert.getCertificateFromP12(storefile, storeentry, storepassword);
145                     }
146                 } catch (Exception JavaDoc e) {
147                     throw new JspException JavaDoc("JCE Exception - keystore could not be loaded: " + e.getMessage(), e);
148                 }
149
150                 // get the public key from the certificate
151
encryptKey = cert.getPublicKey();
152
153                 output = Asymmetric.encrypt(input, encryptKey);
154
155             } else {
156                 PrivateKey JavaDoc decryptKey;
157
158                 try {
159                     // Retrieve the private key (for signing) from one of the three possible keystores
160
if (storefile == null || storefile == "") {
161                         if (pemfile == null || pemfile == "") {
162                             // use PEM string
163
InputStream JavaDoc pemstream = new ByteArrayInputStream JavaDoc(pemstring.getBytes());
164                             decryptKey = CertTools.getPrivatefromPEM(pemstream, "");
165                         } else {
166                             // use PEM store
167
decryptKey = CertTools.getPrivatefromPEM(pemfile, "");
168                         }
169                     } else {
170                         // use PKCS #12 keystore
171
decryptKey = X509Cert.getPrivateFromP12(storefile, storeentry, storepassword);
172                     }
173                 } catch (Exception JavaDoc e) {
174                     throw new JspException JavaDoc("JCE Exception - keystore could not be loaded: " + e.getMessage(), e);
175                 }
176
177                 output = Asymmetric.decrypt(input, decryptKey);
178             }
179         } catch (Exception JavaDoc e) {
180             throw new JspException JavaDoc("JCE Exception: " + e.getMessage(), e);
181         }
182
183         // decide what to do with the result
184
if (var != null) {
185             if (output != null) {
186                 pageContext.setAttribute(var, output, scope);
187             }
188         } else {
189             if (bodyContent != null) {
190                 bodyContent.clearBody();
191             }
192
193             try {
194                 JspWriter JavaDoc w = pageContext.getOut();
195                 w.print(output);
196             } catch (IOException JavaDoc ex) {
197                 throw new JspException JavaDoc(ex.getMessage(), ex);
198             }
199         }
200
201         return EVAL_PAGE;
202     } // doEndTag()
203

204     public void release() {
205         // Cleanup all sensitive information
206
Clean.blank(value);
207         Clean.blank(storepassword);
208         Clean.blank(input);
209         Clean.blank(output);
210
211         super.release();
212     } //release()
213

214     /**
215      * @jsp.attribute
216      * description="Optional attribute, the string to encrypt or decrypt. The body of the tag will be taken if omitted"
217      * type="java.lang.StringBuffer"
218      * required="false"
219      * rtexprvalue="true"
220      */

221     public void setValue(StringBuffer JavaDoc value) {
222         this.value = value;
223     }
224
225     public StringBuffer JavaDoc getValue() {
226         return value;
227     }
228
229     /**
230      * @jsp.attribute
231      * description="Optional attribute, variable to store the encrypted string. The string will be printed if omitted"
232      * type="java.lang.String"
233      * required="false"
234      * rtexprvalue="false"
235      */

236     public void setVar(String JavaDoc var) {
237         this.var = var;
238     }
239
240     public String JavaDoc getVar() {
241         return var;
242     }
243
244     /**
245      * @jsp.attribute
246      * description="Scope of the 'var' attribute. Can be 'page', 'session', 'request' or 'application'. Default is 'page'"
247      * type="java.lang.String"
248      * required="false"
249      * rtexprvalue="false"
250      */

251     public void setScope(String JavaDoc scope) {
252         this.scope = getScope(scope);
253     }
254
255     /**
256      * @jsp.attribute
257      * description="The PKCS#12 (P12) keystore where the private key is stored"
258      * type="java.lang.String"
259      * required="true"
260      * rtexprvalue="true"
261      */

262     public void setStorefile(String JavaDoc storefile) {
263         this.storefile = storefile;
264     }
265
266     /**
267      * @jsp.attribute
268      * description="The PKCS#12 (P12) keystore entry name for private key"
269      * type="java.lang.String"
270      * required="true"
271      * rtexprvalue="true"
272      */

273     public void setStoreentry(String JavaDoc storeentry) {
274         this.storeentry = storeentry;
275     }
276
277     /**
278      * @jsp.attribute
279      * description="The PKCS#12 (P12) keystore password"
280      * type="java.lang.StringBuffer"
281      * required="true"
282      * rtexprvalue="true"
283      */

284     public void setStorepassword(StringBuffer JavaDoc storepassword) {
285         this.storepassword = storepassword;
286     }
287
288     /**
289      * @jsp.attribute
290      * 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 "
291      * type="java.lang.String"
292      * required="false"
293      * rtexprvalue="true"
294      */

295     public void setPemfile(String JavaDoc pemfile) {
296         this.pemfile = pemfile;
297     }
298
299     /**
300      * @jsp.attribute
301      * 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"
302      * type="java.lang.String"
303      * required="false"
304      * rtexprvalue="true"
305      */

306     public void setPemstring(String JavaDoc pemstring) {
307         this.pemstring = pemstring;
308     }
309
310     /**
311      * @jsp.attribute
312      * description="The action to perform. 'encrypt' for encryption, 'decrypt' for decryption. Default is 'encrypt'"
313      * type="java.lang.String"
314      * required="false"
315      * rtexprvalue="false"
316      */

317     public void setAction(String JavaDoc action) {
318         this.action = action;
319     }
320 }
Popular Tags