KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2   Name: SelfSign.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.Security JavaDoc;
36 import java.security.cert.X509Certificate JavaDoc;
37
38 /**
39  * JSP tag used for generating self-signed X.509 certificates
40  *
41  * @jsp.tag
42  * name="selfsign"
43  * display-name="SelfSign"
44  * body-content="empty"
45  * example="<%-- Create a self-signed certificate --%>

46  * 	<jce:selfsign

47  * 	subjectdn=

48  * 		\"C=BE,

49  * 		O=NET, 

50  * 		OU=Sourceforge,

51  * 		CN=CertAuthority,

52  * 		EmailAddress=info@certauthority.org\"

53  * 	fingerprint=\"fp\"

54  * 	serialnumber=\"sn\"

55  * 

56  * 	storefile=\"C:/keystores/ca.p12\"

57  * 	storeentry=\"ca\"

58  * 	storepassword=\"&t;%= new StringBuffer(\"password\") %>\"/>"
59  *
60  * description="JSP tag used for generating self-signed X.509 certificates"
61  *
62  * @author Gert Van Ham
63  * @author hamgert@users.sourceforge.net
64  * @author http://jcetaglib.sourceforge.net
65  * @version $Id: SelfSign.java,v 1.5 2004/04/15 07:28:36 hamgert Exp $
66  */

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

78     private String JavaDoc subjectdn;
79     private long validity = 365;
80     private boolean isca = true;
81
82     private String JavaDoc netscapeextensions;
83
84     // return info
85
private int scope = PageContext.PAGE_SCOPE;
86     private String JavaDoc serialnumber;
87     private String JavaDoc fingerprint;
88
89     // return certificates...
90

91     // ...P12 keystore...
92
private String JavaDoc storefile; // tag attribute
93
private String JavaDoc storeentry; // tag attribute
94
private StringBuffer JavaDoc storepassword; // tag attribute
95

96     // ... OR variables
97
private String JavaDoc certificate;
98     private String JavaDoc privatekey;
99
100     private StringBuffer JavaDoc pkey;
101
102     public static int getScope(String JavaDoc scope) {
103         int ret = PageContext.PAGE_SCOPE; // default
104

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

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

174     public void release() {
175         // Cleanup all sensitive information
176
Clean.blank(pkey);
177         Clean.blank(storepassword);
178
179         super.release();
180     } //release()
181

182     /**
183      * @jsp.attribute
184      * description="Keypair algorithm. 'RSA', 'DSA' or 'EC-DSA'. Default is 'RSA'"
185      * type="java.lang.String"
186      * required="false"
187      * rtexprvalue="true"
188      */

189     public void setKeypairalgorithm(String JavaDoc keypairalgorithm) {
190         this.keypairalgorithm = keypairalgorithm;
191     }
192
193     /**
194      * @jsp.attribute
195      * description="Key length. 512, 1024 or 2048. Default is 1024. Please note that not all products support key lengths greater than 1024"
196      * type="java.lang.Integer"
197      * required="false"
198      * rtexprvalue="true"
199      */

200     public void setKeylength(int keylength) {
201         this.keylength = keylength;
202     }
203
204     /**
205      * @jsp.attribute
206      * description="Signature algorithm. Default is 'MD5WithRSAEncryption'"
207      * type="java.lang.String"
208      * required="false"
209      * rtexprvalue="true"
210      */

211     public void setSignaturealgorithm(String JavaDoc signaturealgorithm) {
212         this.signaturealgorithm = signaturealgorithm;
213     }
214
215     /**
216      * @jsp.attribute
217      * 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 ...')"
218      * type="java.lang.String"
219      * required="true"
220      * rtexprvalue="true"
221      */

222     public void setSubjectdn(String JavaDoc subjectdn) {
223         this.subjectdn = subjectdn;
224     }
225
226     /**
227      * @jsp.attribute
228      * description="The validity of the certificate in days. Default is 365"
229      * type="java.lang.Long"
230      * required="false"
231      * rtexprvalue="true"
232      */

233     public void setValidity(long validity) {
234         this.validity = validity;
235     }
236
237     /**
238      * @jsp.attribute
239      * 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"
240      * type="java.lang.Boolean"
241      * required="false"
242      * rtexprvalue="true"
243      */

244     public void setIsca(boolean isca) {
245         this.isca = isca;
246     }
247
248     /**
249      * @jsp.attribute
250      * 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:


251      * 'CA': this certificate can be used as SSL Certificate Authority, Email Signer and Object Signer

252      * 'SERVER': this certificate can be used as SSL Server.

253      * 'CLIENT': this certificate can be used as SSL Client, Email Recipient and Object Signer

254      * 'ALL': this certificate can be used for all above purposes."
255      * type="java.lang.String"
256      * required="false"
257      * rtexprvalue="true"
258      */

259     public void setNetscapeextensions(String JavaDoc netscapeextensions) {
260         this.netscapeextensions = netscapeextensions;
261     }
262
263     /**
264      * @jsp.attribute
265      * description="Scope of the return variables. Can be 'page', 'session', 'request' or 'application'. Default is 'page'"
266      * type="java.lang.String"
267      * required="false"
268      * rtexprvalue="false"
269      */

270     public void setScope(String JavaDoc scope) {
271         this.scope = getScope(scope);
272     }
273
274     /**
275      * @jsp.attribute
276      * description="Variable to store the certificate serial number"
277      * type="java.lang.String"
278      * required="true"
279      * rtexprvalue="false"
280      */

281     public void setSerialnumber(String JavaDoc serialnumber) {
282         this.serialnumber = serialnumber;
283     }
284
285     public String JavaDoc getSerialnumber() {
286         return serialnumber;
287     }
288
289     /**
290      * @jsp.attribute
291      * description="Variable to store the certificate fingerprint (SHA-1)"
292      * type="java.lang.String"
293      * required="true"
294      * rtexprvalue="false"
295      */

296     public void setFingerprint(String JavaDoc fingerprint) {
297         this.fingerprint = fingerprint;
298     }
299
300     public String JavaDoc getFingerprint() {
301         return fingerprint;
302     }
303
304     /**
305      * @jsp.attribute
306      * description="The PKCS#12 (P12) keystore to store the certificate"
307      * type="java.lang.String"
308      * required="false"
309      * rtexprvalue="true"
310      */

311     public void setStorefile(String JavaDoc storefile) {
312         this.storefile = storefile;
313     }
314
315     /**
316      * @jsp.attribute
317      * description="The PKCS#12 (P12) keystore entry name for this certificate"
318      * type="java.lang.String"
319      * required="false"
320      * rtexprvalue="true"
321      */

322     public void setStoreentry(String JavaDoc storeentry) {
323         this.storeentry = storeentry;
324     }
325
326     /**
327      * @jsp.attribute
328      * description="The PKCS#12 (P12) keystore password"
329      * type="java.lang.StringBuffer"
330      * required="false"
331      * rtexprvalue="true"
332      */

333     public void setStorepassword(StringBuffer JavaDoc storepassword) {
334         this.storepassword = storepassword;
335     }
336
337     /**
338      * @jsp.attribute
339      * description="Variable to store the certificate as a PEM formatted string"
340      * type="java.lang.String"
341      * required="false"
342      * rtexprvalue="false"
343      */

344     public void setCertificate(String JavaDoc certificate) {
345         this.certificate = certificate;
346     }
347
348     public String JavaDoc getCertificate() {
349         return certificate;
350     }
351
352     /**
353      * @jsp.attribute
354      * description="Variable to store the private key as a PEM formatted StringBuffer"
355      * type="java.lang.String"
356      * required="false"
357      * rtexprvalue="false"
358      */

359     public void setPrivatekey(String JavaDoc privatekey) {
360         this.privatekey = privatekey;
361     }
362
363     public String JavaDoc getPrivatekey() {
364         return privatekey;
365     }
366 }
Popular Tags