KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sourceforge > jcetaglib > taglib > x509 > Sign


1 /*
2   Name: Sign.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.x509;
21
22 import net.sourceforge.jcetaglib.lib.CertTools;
23 import net.sourceforge.jcetaglib.lib.Clean;
24 import net.sourceforge.jcetaglib.lib.X509Cert;
25 import net.sourceforge.jcetaglib.tools.KeyTools;
26 import org.bouncycastle.jce.provider.BouncyCastleProvider;
27 import org.bouncycastle.util.encoders.Base64;
28
29 import javax.servlet.jsp.JspException JavaDoc;
30 import javax.servlet.jsp.PageContext JavaDoc;
31 import javax.servlet.jsp.tagext.TagSupport JavaDoc;
32 import java.io.FileOutputStream JavaDoc;
33 import java.security.KeyPair JavaDoc;
34 import java.security.KeyStore JavaDoc;
35 import java.security.PrivateKey JavaDoc;
36 import java.security.Security JavaDoc;
37 import java.security.cert.X509Certificate JavaDoc;
38
39 /**
40  * JSP tag used for generating signed X.509 certificates
41  *
42  * @jsp.tag
43  * name="sign"
44  * display-name="Sign"
45  * body-content="empty"
46  * example="<%-- Create a signed certificate --%>

47  * <jce:sign

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

49  * 	fingerprint=\"fp\"

50  * 	serialnumber=\"sn\" 

51  * 	signfile=\"C:/keystores/ca.p12\"

52  * 	signentry=\"ca\"

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

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

55  * 	storeentry=\"user\"

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

57  * 	netscapeextensions=\"client\"/>"
58  *
59  * description="JSP tag used for generating signed X.509 certificates"
60  *
61  * @author Gert Van Ham
62  * @author hamgert@users.sourceforge.net
63  * @author http://jcetaglib.sourceforge.net
64  * @version $Id: Sign.java,v 1.5 2004/04/15 07:28:36 hamgert Exp $
65  */

66
67 public class Sign extends TagSupport JavaDoc {
68     private static final String JavaDoc PAGE = "page";
69     private static final String JavaDoc REQUEST = "request";
70     private static final String JavaDoc SESSION = "session";
71     private static final String JavaDoc APPLICATION = "application";
72
73     private String JavaDoc keypairalgorithm = "RSA"; // tag attribute
74
private int keylength = 1024; // tag attribute
75
private String JavaDoc signaturealgorithm = "MD5WithRSAEncryption"; // tag attribute
76

77     private String JavaDoc subjectdn;
78     private long validity = 365;
79     private boolean isca = false;
80
81     private String JavaDoc crldisturi;
82
83     private String JavaDoc netscapeextensions;
84
85     private String JavaDoc signfile; // tag attribute
86
private String JavaDoc signentry; // tag attribute
87
private StringBuffer JavaDoc signpassword; // tag attribute
88

89     // return info
90
private int scope = PageContext.PAGE_SCOPE;
91     private String JavaDoc serialnumber;
92     private String JavaDoc fingerprint;
93
94     // return certificates...
95

96     // ...P12 keystore...
97
private String JavaDoc storefile; // tag attribute
98
private String JavaDoc storeentry; // tag attribute
99
private StringBuffer JavaDoc storepassword; // tag attribute
100

101     // ... OR variables
102
private String JavaDoc certificate;
103     private String JavaDoc privatekey;
104
105     private StringBuffer JavaDoc pkey;
106
107     public static int getScope(String JavaDoc scope) {
108         int ret = PageContext.PAGE_SCOPE; // default
109

110         if (REQUEST.equalsIgnoreCase(scope))
111             ret = PageContext.REQUEST_SCOPE;
112         else if (SESSION.equalsIgnoreCase(scope))
113             ret = PageContext.SESSION_SCOPE;
114         else if (APPLICATION.equalsIgnoreCase(scope))
115             ret = PageContext.APPLICATION_SCOPE;
116         else if (PAGE.equalsIgnoreCase(scope))
117             ret = PageContext.PAGE_SCOPE;
118
119         return ret;
120     } //getScope()
121

122     public int doEndTag() throws JspException JavaDoc {
123
124         // Add Bouncy Castle provider
125
Security.addProvider(new BouncyCastleProvider());
126
127         try {
128             // read CA certificate & private key
129
PrivateKey JavaDoc CAprivateKey = X509Cert.getPrivateFromP12(signfile, signentry, signpassword);
130             X509Certificate JavaDoc caCert = X509Cert.getCertificateFromP12(signfile, signentry, signpassword);
131
132             // generate keypair
133
KeyPair JavaDoc p = X509Cert.generateKeyPair(keypairalgorithm, keylength, null);
134
135             // generate certificate
136
X509Certificate JavaDoc cert = X509Cert.sign(p.getPublic()
137                     , CAprivateKey
138                     , caCert
139                     , signaturealgorithm
140                     , validity
141                     , subjectdn
142                     , isca
143                     , crldisturi
144                     , netscapeextensions);
145
146
147             if (storefile == null || storefile == "") {
148                 // Return certificate as string
149
byte output[] = cert.getEncoded();
150                 byte certB64[] = Base64.encode(output);
151
152                 pageContext.setAttribute(certificate, "-----BEGIN CERTIFICATE-----\n" + new String JavaDoc(certB64) + "\n-----END CERTIFICATE-----", scope);
153
154                 // Return private key as string
155
byte keyoutput[] = p.getPrivate().getEncoded();
156                 byte keyB64[] = Base64.encode(keyoutput);
157
158                 pkey = new StringBuffer JavaDoc("-----BEGIN PRIVATE KEY-----\n");
159                 pkey.append(new String JavaDoc(keyB64));
160                 pkey.append("\n-----END PRIVATE KEY-----");
161
162                 pageContext.setAttribute(privatekey, pkey, scope);
163
164                 Clean.blank(keyoutput);
165                 Clean.blank(keyB64);
166
167             } else {
168                 // Store certificate in PKCS#12 store
169
KeyStore JavaDoc store = KeyStore.getInstance("PKCS12", "BC");
170
171                 store = KeyTools.createP12(storeentry, p.getPrivate(), cert, caCert);
172                 store.store(new FileOutputStream JavaDoc(storefile), storepassword.toString().toCharArray());
173             }
174
175             // return serialnumber and fingerprint
176
pageContext.setAttribute(serialnumber, cert.getSerialNumber().toString(), scope);
177             pageContext.setAttribute(fingerprint, CertTools.getFingerprintAsString(cert), scope);
178         } catch (Exception JavaDoc e) {
179             throw new JspException JavaDoc("JCE Exception: Unable to generate certificate: "
180                     + e.getMessage(), e);
181         }
182
183         return EVAL_PAGE;
184     } // doEndTag()
185

186     public void release() {
187         // Cleanup all sensitive information
188
Clean.blank(pkey);
189         Clean.blank(storepassword);
190         Clean.blank(signpassword);
191
192         super.release();
193     } //release()
194

195
196     /**
197      * @jsp.attribute
198      * description="Keypair algorithm. 'RSA', 'DSA' or 'EC-DSA'. Default is 'RSA'"
199      * type="java.lang.String"
200      * required="false"
201      * rtexprvalue="true"
202      */

203     public void setKeypairalgorithm(String JavaDoc keypairalgorithm) {
204         this.keypairalgorithm = keypairalgorithm;
205     }
206
207     /**
208      * @jsp.attribute
209      * description="Key length. 512, 1024 or 2048. Default is 1024. Please note that not all products support key lengths greater than 1024"
210      * type="java.lang.Integer"
211      * required="false"
212      * rtexprvalue="true"
213      */

214     public void setKeylength(int keylength) {
215         this.keylength = keylength;
216     }
217
218     /**
219      * @jsp.attribute
220      * description="Signature algorithm. Default is 'MD5WithRSAEncryption'"
221      * type="java.lang.String"
222      * required="false"
223      * rtexprvalue="true"
224      */

225     public void setSignaturealgorithm(String JavaDoc signaturealgorithm) {
226         this.signaturealgorithm = signaturealgorithm;
227     }
228
229     /**
230      * @jsp.attribute
231      * 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 ...')"
232      * type="java.lang.String"
233      * required="true"
234      * rtexprvalue="true"
235      */

236     public void setSubjectdn(String JavaDoc subjectdn) {
237         this.subjectdn = subjectdn;
238     }
239
240     /**
241      * @jsp.attribute
242      * description="The validity of the certificate in days. Default is 365"
243      * type="java.lang.Long"
244      * required="false"
245      * rtexprvalue="true"
246      */

247     public void setValidity(long validity) {
248         this.validity = validity;
249     }
250
251     /**
252      * @jsp.attribute
253      * 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"
254      * type="java.lang.Boolean"
255      * required="false"
256      * rtexprvalue="true"
257      */

258     public void setIsca(boolean isca) {
259         this.isca = isca;
260     }
261
262     /**
263      * @jsp.attribute
264      * description="CRL (Certificate Revocation List) distribution URI extension. Default is none"
265      * type="java.lang.String"
266      * required="false"
267      * rtexprvalue="true"
268      */

269     public void setCrldisturi(String JavaDoc crldisturi) {
270         this.crldisturi = crldisturi;
271     }
272
273     /**
274      * @jsp.attribute
275      * 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
276      * 'CA': this certificate can be used as SSL Certificate Authority, Email Signer and Object Signer&#10
277      * 'SERVER': this certificate can be used as SSL Server.&#10
278      * 'CLIENT': this certificate can be used as SSL Client, Email Recipient and Object Signer&#10
279      * 'ALL': this certificate can be used for all above purposes."
280      * type="java.lang.String"
281      * required="false"
282      * rtexprvalue="true"
283      */

284     public void setNetscapeextensions(String JavaDoc netscapeextensions) {
285         this.netscapeextensions = netscapeextensions;
286     }
287
288     /**
289      * @jsp.attribute
290      * description="The PKCS#12 (P12) keystore where the CA signing certificate is stored"
291      * type="java.lang.String"
292      * required="true"
293      * rtexprvalue="true"
294      */

295     public void setSignfile(String JavaDoc signfile) {
296         this.signfile = signfile;
297     }
298
299     /**
300      * @jsp.attribute
301      * description="The PKCS#12 (P12) keystore entry name for the CA signing certificate"
302      * type="java.lang.String"
303      * required="true"
304      * rtexprvalue="true"
305      */

306     public void setSignentry(String JavaDoc signentry) {
307         this.signentry = signentry;
308     }
309
310     /**
311      * @jsp.attribute
312      * description="The PKCS#12 (P12) keystore signing password"
313      * type="java.lang.StringBuffer"
314      * required="true"
315      * rtexprvalue="true"
316      */

317     public void setSignpassword(StringBuffer JavaDoc signpassword) {
318         this.signpassword = signpassword;
319     }
320
321     /**
322      * @jsp.attribute
323      * description="Scope of the return variables. Can be 'page', 'session', 'request' or 'application'. Default is 'page'"
324      * type="java.lang.String"
325      * required="false"
326      * rtexprvalue="false"
327      */

328     public void setScope(String JavaDoc scope) {
329         this.scope = getScope(scope);
330     }
331
332     /**
333      * @jsp.attribute
334      * description="Variable to store the certificate serial number"
335      * type="java.lang.String"
336      * required="true"
337      * rtexprvalue="false"
338      */

339     public void setSerialnumber(String JavaDoc serialnumber) {
340         this.serialnumber = serialnumber;
341     }
342
343     public String JavaDoc getSerialnumber() {
344         return serialnumber;
345     }
346
347     /**
348      * @jsp.attribute
349      * description="Variable to store the certificate fingerprint (SHA-1)"
350      * type="java.lang.String"
351      * required="true"
352      * rtexprvalue="false"
353      */

354     public void setFingerprint(String JavaDoc fingerprint) {
355         this.fingerprint = fingerprint;
356     }
357
358     public String JavaDoc getFingerprint() {
359         return fingerprint;
360     }
361
362     /**
363      * @jsp.attribute
364      * description="The PKCS#12 (P12) keystore to store the certificate"
365      * type="java.lang.String"
366      * required="false"
367      * rtexprvalue="true"
368      */

369     public void setStorefile(String JavaDoc storefile) {
370         this.storefile = storefile;
371     }
372
373     /**
374      * @jsp.attribute
375      * description="The PKCS#12 (P12) keystore entry name for this certificate"
376      * type="java.lang.String"
377      * required="false"
378      * rtexprvalue="true"
379      */

380     public void setStoreentry(String JavaDoc storeentry) {
381         this.storeentry = storeentry;
382     }
383
384     /**
385      * @jsp.attribute
386      * description="The PKCS#12 (P12) keystore password"
387      * type="java.lang.StringBuffer"
388      * required="false"
389      * rtexprvalue="true"
390      */

391     public void setStorepassword(StringBuffer JavaDoc storepassword) {
392         this.storepassword = storepassword;
393     }
394
395     /**
396      * @jsp.attribute
397      * description="Variable to store the certificate as a PEM formatted string"
398      * type="java.lang.String"
399      * required="false"
400      * rtexprvalue="false"
401      */

402     public void setCertificate(String JavaDoc certificate) {
403         this.certificate = certificate;
404     }
405
406     public String JavaDoc getCertificate() {
407         return certificate;
408     }
409
410     /**
411      * @jsp.attribute
412      * description="Variable to store the private key as a PEM formatted StringBuffer"
413      * type="java.lang.String"
414      * required="false"
415      * rtexprvalue="false"
416      */

417     public void setPrivatekey(String JavaDoc privatekey) {
418         this.privatekey = privatekey;
419     }
420
421     public String JavaDoc getPrivatekey() {
422         return privatekey;
423     }
424 }
Popular Tags