KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2   Name: EncryptAndSign.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.CertTools;
23 import net.sourceforge.jcetaglib.lib.Clean;
24 import net.sourceforge.jcetaglib.lib.Hybrid;
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.cert.X509Certificate JavaDoc;
36
37 /**
38  * JSP tag used for encrypting & signing data
39  *
40  * @jsp.tag
41  * name="encryptandsign"
42  * display-name="EncryptAndSign"
43  * body-content="JSP"
44  * example="
45  * <jce:encryptandsign

46  * 	var=\"foralice\"

47  * 	value=\"<%= new StringBuffer(\"Encrypt this string\") %>\"

48  * 	scope=\"page\"

49  * 	storefile=\"C:/keystores/bob.p12\"

50  * 	storeentry=\"user\"

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

52  * 	recpemfile=\"C:/keystores/alice.cert\"/>"
53  *
54  * description="JSP tag used for encrypting & signing data"
55  *
56  * @author Gert Van Ham
57  * @author hamgert@users.sourceforge.net
58  * @author http://jcetaglib.sourceforge.net
59  * @version $Id: EncryptAndSign.java,v 1.5 2004/04/15 07:28:35 hamgert Exp $
60  */

61 public class EncryptAndSign extends BodyTagSupport JavaDoc {
62     private static final String JavaDoc PAGE = "page";
63     private static final String JavaDoc REQUEST = "request";
64     private static final String JavaDoc SESSION = "session";
65     private static final String JavaDoc APPLICATION = "application";
66
67     private StringBuffer JavaDoc value; // tag attribute
68
private String JavaDoc var; // tag attribute
69
private int scope = PageContext.PAGE_SCOPE; // tag attribute
70

71     private String JavaDoc file; // tag attribute
72
private String JavaDoc newfile; // tag attribute
73

74     private String JavaDoc signame = "MD5withRSA"; // tag attribute
75
private String JavaDoc algorithm = "AES"; // tag attribute
76
private String JavaDoc seed; // tag attribute
77
private int strength = 256; // tag attribute
78
private String JavaDoc mode = "CBC"; // tag attribute
79
private String JavaDoc padding = "PKCS7Padding"; // tag attribute
80

81     /* Attributes for sender's X.509 keystore */
82
83     // P12 keystore
84
private String JavaDoc storefile; // tag attribute
85
private String JavaDoc storeentry; // tag attribute
86
private StringBuffer JavaDoc storepassword; // tag attribute
87

88     /* Attributes for receiver's certificate */
89
90     // receiver's certificate as string
91
private String JavaDoc recpemstring; // tag attribute
92

93     // ... OR as PEM file
94
private String JavaDoc recpemfile; // tag attribute
95

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

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

102         if (REQUEST.equalsIgnoreCase(scope))
103             ret = PageContext.REQUEST_SCOPE;
104         else if (SESSION.equalsIgnoreCase(scope))
105             ret = PageContext.SESSION_SCOPE;
106         else if (APPLICATION.equalsIgnoreCase(scope))
107             ret = PageContext.APPLICATION_SCOPE;
108         else if (PAGE.equalsIgnoreCase(scope))
109             ret = PageContext.PAGE_SCOPE;
110
111         return ret;
112     } //getScope()
113

114     public int doEndTag() throws JspException JavaDoc {
115         X509Certificate JavaDoc cert = null;
116         X509Certificate JavaDoc reccert = null;
117         PrivateKey JavaDoc signingKey = null;
118
119         // determine the value by...
120
if (value != null) {
121             // ... reading our attribute
122
input = value;
123         } else {
124             // ... retrieving and trimming our body
125
if (bodyContent == null || bodyContent.getString() == null) {
126                 input = new StringBuffer JavaDoc("");
127             } else {
128                 input = new StringBuffer JavaDoc(bodyContent.getString().trim());
129             }
130         }
131
132         // retrieve the sender's private key (for signing) & public key
133
try {
134             signingKey = X509Cert.getPrivateFromP12(storefile, storeentry, storepassword);
135             cert = X509Cert.getCertificateFromP12(storefile, storeentry, storepassword);
136         } catch (Exception JavaDoc e) {
137             throw new JspException JavaDoc("JCE Exception - keystore could not be loaded: " + e.getMessage(), e);
138         }
139
140         // loading the receiver's public key
141
try {
142             if (recpemfile == null || recpemfile == "") {
143                 // use PEM string
144
InputStream JavaDoc pemstream = new ByteArrayInputStream JavaDoc(recpemstring.getBytes());
145                 reccert = CertTools.getCertfromPEM(pemstream);
146             } else {
147                 // use PEM store
148
reccert = CertTools.getCertfromPEM(recpemfile);
149             }
150         } catch (Exception JavaDoc e) {
151             throw new JspException JavaDoc("JCE Exception - PEM could not be loaded: " + e.getMessage(), e);
152         }
153
154         // encrypt and sign
155
try {
156             if (file != null) {
157                 if (seed == null) {
158                     Hybrid.encryptFileAndSign(file
159                             , newfile
160                             , reccert.getPublicKey()
161                             , signingKey
162                             , cert
163                             , signame
164                             , algorithm
165                             , null
166                             , strength
167                             , mode
168                             , padding);
169                 } else {
170                     Hybrid.encryptFileAndSign(file
171                             , newfile
172                             , reccert.getPublicKey()
173                             , signingKey
174                             , cert
175                             , signame
176                             , algorithm
177                             , seed.getBytes()
178                             , strength
179                             , mode
180                             , padding);
181                 }
182             } else {
183                 if (seed == null) {
184                     output = Hybrid.encryptAndSign(input
185                             , reccert.getPublicKey()
186                             , signingKey
187                             , cert
188                             , signame
189                             , algorithm
190                             , null
191                             , strength
192                             , mode
193                             , padding);
194                 } else {
195                     output = Hybrid.encryptAndSign(input
196                             , reccert.getPublicKey()
197                             , signingKey
198                             , cert
199                             , signame
200                             , algorithm
201                             , seed.getBytes()
202                             , strength
203                             , mode
204                             , padding);
205                 }
206             }
207         } catch (Exception JavaDoc e) {
208             throw new JspException JavaDoc("JCE Exception: " + e.getMessage(), e);
209         }
210
211         // decide what to do with the result
212
if (var != null) {
213             if (output != null) {
214                 pageContext.setAttribute(var, output, scope);
215             }
216         } else {
217             if (file == null || file == "") {
218                 if (bodyContent != null) {
219                     bodyContent.clearBody();
220                 }
221
222                 try {
223                     JspWriter JavaDoc w = pageContext.getOut();
224                     w.print(output);
225                 } catch (IOException JavaDoc ex) {
226                     throw new JspException JavaDoc(ex.getMessage(), ex);
227                 }
228             }
229         }
230
231         signingKey = null;
232
233         return EVAL_PAGE;
234     }
235
236     public void release() {
237         // Cleanup all sensitive information
238
Clean.blank(value);
239         Clean.blank(storepassword);
240         Clean.blank(input);
241         Clean.blank(output);
242
243         super.release();
244     } //release()
245

246     /**
247      * @jsp.attribute
248      * description="Optional attribute, the string to encrypt or decrypt. The body of the tag will be taken if omitted"
249      * type="java.lang.StringBuffer"
250      * required="false"
251      * rtexprvalue="true"
252      */

253     public void setValue(StringBuffer JavaDoc value) {
254         this.value = value;
255     }
256
257     public StringBuffer JavaDoc getValue() {
258         return value;
259     }
260
261     /**
262      * @jsp.attribute
263      * description="Optional attribute, variable to store the encrypted string. The string will be printed if omitted"
264      * type="java.lang.String"
265      * required="false"
266      * rtexprvalue="false"
267      */

268     public void setVar(String JavaDoc var) {
269         this.var = var;
270     }
271
272     public String JavaDoc getVar() {
273         return var;
274     }
275
276     /**
277      * @jsp.attribute
278      * description="Scope of the 'var' attribute. Can be 'page', 'session', 'request' or 'application'. Default is 'page'"
279      * type="java.lang.String"
280      * required="false"
281      * rtexprvalue="false"
282      */

283     public void setScope(String JavaDoc scope) {
284         this.scope = getScope(scope);
285     }
286
287     /**
288      * @jsp.attribute
289      * description="The signature algorithm. Default is 'MD5withRSA'"
290      * type="java.lang.String"
291      * required="false"
292      * rtexprvalue="true"
293      */

294     public void setSigname(String JavaDoc signame) {
295         this.signame = signame;
296     }
297
298     /**
299      * @jsp.attribute
300      * description="The key algorithm. Default is 'AES'"
301      * type="java.lang.String"
302      * required="false"
303      * rtexprvalue="true"
304      */

305     public void setAlgorithm(String JavaDoc algorithm) {
306         this.algorithm = algorithm;
307     }
308
309     /**
310      * @jsp.attribute
311      * description="Optional seed for SecureRandom "
312      * type="java.lang.String"
313      * required="false"
314      * rtexprvalue="true"
315      */

316     public void setSeed(String JavaDoc seed) {
317         this.seed = seed;
318     }
319
320     /**
321      * @jsp.attribute
322      * description="The key size in bits (integer value). Values depends on the used algorithm (see next paragraph). Default is 256 (for AES)"
323      * type="java.lang.String"
324      * required="false"
325      * rtexprvalue="true"
326      */

327     public void setStrength(int strength) {
328         this.strength = strength;
329     }
330
331     /**
332      * @jsp.attribute
333      * description="Encryption mode. Default is 'CBC'"
334      * type="java.lang.String"
335      * required="false"
336      * rtexprvalue="true"
337      */

338     public void setMode(String JavaDoc mode) {
339         this.mode = mode;
340     }
341
342     /**
343      * @jsp.attribute
344      * description="Padding scheme. Default is 'PKCS7Padding'"
345      * type="java.lang.String"
346      * required="false"
347      * rtexprvalue="true"
348      */

349     public void setPadding(String JavaDoc padding) {
350         this.padding = padding;
351     }
352
353     /**
354      * @jsp.attribute
355      * description="The PKCS#12 (P12) keystore where the private key is stored"
356      * type="java.lang.String"
357      * required="true"
358      * rtexprvalue="true"
359      */

360     public void setStorefile(String JavaDoc storefile) {
361         this.storefile = storefile;
362     }
363
364     /**
365      * @jsp.attribute
366      * description="The PKCS#12 (P12) keystore entry name for private key"
367      * type="java.lang.String"
368      * required="true"
369      * rtexprvalue="true"
370      */

371     public void setStoreentry(String JavaDoc storeentry) {
372         this.storeentry = storeentry;
373     }
374
375     /**
376      * @jsp.attribute
377      * description="The PKCS#12 (P12) keystore password"
378      * type="java.lang.StringBuffer"
379      * required="true"
380      * rtexprvalue="true"
381      */

382     public void setStorepassword(StringBuffer JavaDoc storepassword) {
383         this.storepassword = storepassword;
384     }
385
386     /**
387      * @jsp.attribute
388      * description="The receiver's certificate stored in a PEM file"
389      * type="java.lang.String"
390      * required="false"
391      * rtexprvalue="true"
392      */

393     public void setRecpemfile(String JavaDoc recpemfile) {
394         this.recpemfile = recpemfile;
395     }
396
397     /**
398      * @jsp.attribute
399      * description="The receiver's certificate as a PEM formatted string"
400      * type="java.lang.String"
401      * required="false"
402      * rtexprvalue="true"
403      */

404     public void setRecpemstring(String JavaDoc recpemstring) {
405         this.recpemstring = recpemstring;
406     }
407
408     /**
409      * @jsp.attribute
410      * description="Encrypts a file instead of a string"
411      * type="java.lang.String"
412      * required="false"
413      * rtexprvalue="true"
414      */

415     public void setFile(String JavaDoc file) {
416         this.file = file;
417     }
418
419     /**
420      * @jsp.attribute
421      * description="File(name) to store the encrypted data"
422      * type="java.lang.String"
423      * required="false"
424      * rtexprvalue="true"
425      */

426     public void setNewfile(String JavaDoc newfile) {
427         this.newfile = newfile;
428     }
429 }
Popular Tags