KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > geronimo > console > core > keystore > KeyStoreGBean


1 /**
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License. You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */

17
18 package org.apache.geronimo.console.core.keystore;
19
20 import java.io.ByteArrayInputStream JavaDoc;
21 import java.io.ByteArrayOutputStream JavaDoc;
22 import java.io.File JavaDoc;
23 import java.io.FileInputStream JavaDoc;
24 import java.io.FileOutputStream JavaDoc;
25 import java.io.InputStream JavaDoc;
26 import java.math.BigInteger JavaDoc;
27 import java.security.KeyPair JavaDoc;
28 import java.security.KeyPairGenerator JavaDoc;
29 import java.security.KeyStore JavaDoc;
30 import java.security.KeyStoreException JavaDoc;
31 import java.security.PrivateKey JavaDoc;
32 import java.security.PublicKey JavaDoc;
33 import java.security.cert.Certificate JavaDoc;
34 import java.security.cert.CertificateFactory JavaDoc;
35 import java.security.cert.X509Certificate JavaDoc;
36 import java.util.ArrayList JavaDoc;
37 import java.util.Collection JavaDoc;
38 import java.util.Date JavaDoc;
39 import java.util.Enumeration JavaDoc;
40 import java.util.Hashtable JavaDoc;
41 import java.util.Iterator JavaDoc;
42 import java.util.List JavaDoc;
43 import java.util.Vector JavaDoc;
44
45 import org.apache.commons.logging.Log;
46 import org.apache.commons.logging.LogFactory;
47 import org.apache.geronimo.gbean.GBeanInfo;
48 import org.apache.geronimo.gbean.GBeanInfoBuilder;
49 import org.apache.geronimo.gbean.GBeanLifecycle;
50 import org.apache.geronimo.gbean.WaitingException;
51 import org.apache.geronimo.j2ee.j2eeobjectnames.NameFactory;
52 import org.apache.geronimo.system.serverinfo.ServerInfo;
53 import org.apache.geronimo.util.asn1.ASN1Set;
54 import org.apache.geronimo.util.asn1.DEROutputStream;
55 import org.apache.geronimo.util.asn1.x509.X509Name;
56 import org.apache.geronimo.util.encoders.Base64;
57 import org.apache.geronimo.util.jce.PKCS10CertificationRequest;
58 import org.apache.geronimo.util.jce.X509Principal;
59 import org.apache.geronimo.util.jce.X509V1CertificateGenerator;
60
61 public class KeyStoreGBean implements GBeanLifecycle {
62
63     private static Log log = LogFactory.getLog(KeyStoreGBean.class);
64
65     private String JavaDoc keyStoreType;
66
67     private String JavaDoc keyStoreProvider;
68
69     private String JavaDoc keyStoreLocation;
70
71     private String JavaDoc keyStorePassword;
72
73     private String JavaDoc keyPassword;
74
75     private KeyStore JavaDoc keystore;
76
77     // Used to resolve keystore path.
78
private ServerInfo serverInfo;
79
80     public KeyStoreGBean() {
81         keyPassword = new String JavaDoc("");
82     }
83
84     public void doStart() throws WaitingException, Exception JavaDoc {
85
86         //Security.addProvider(new BouncyCastleProvider());
87

88         this.keystore = KeyStore.getInstance(keyStoreType);
89
90         boolean keystoreExistsFlag = true;
91         InputStream JavaDoc is = null;
92
93         try {
94             File JavaDoc keyStore = serverInfo.resolveServer(this.keyStoreLocation);
95             log.debug("loading keystore from " + keyStore);
96             is = new java.io.FileInputStream JavaDoc(keyStore);
97             this.keystore.load(is, this.keyStorePassword.toCharArray());
98         } catch (java.io.FileNotFoundException JavaDoc e) {
99             keystoreExistsFlag = false;
100         } finally {
101             try {
102                 if (is != null) {
103                     is.close();
104                 }
105             } catch (Exception JavaDoc e) {
106             }
107         }
108
109         if (keystoreExistsFlag == false) {
110             keystore.load(null, keyStorePassword.toCharArray());
111         }
112     }
113
114     public void doStop() throws WaitingException, Exception JavaDoc {
115     }
116
117     public void doFail() {
118     }
119
120     public void setKeyStoreType(String JavaDoc keyStoreType) {
121         this.keyStoreType = keyStoreType;
122     }
123
124     public String JavaDoc getKeyStoreType() {
125         return this.keyStoreType;
126     }
127
128     public void setKeyStoreProvider(String JavaDoc keyStoreProvider) {
129         this.keyStoreProvider = keyStoreProvider;
130     }
131
132     public String JavaDoc getKeyStoreProvider() {
133         return this.keyStoreProvider;
134     }
135
136     public void setKeyStoreLocation(String JavaDoc keyStoreLocation) {
137         this.keyStoreLocation = keyStoreLocation;
138     }
139
140     public ServerInfo getServerInfo() {
141         return serverInfo;
142     }
143
144     public void setServerInfo(ServerInfo serverInfo) {
145         this.serverInfo = serverInfo;
146     }
147
148     public String JavaDoc getKeyStoreLocation() {
149         return this.keyStoreLocation;
150     }
151
152     public void setKeyStorePassword(String JavaDoc keyStorePassword) {
153         this.keyStorePassword = keyStorePassword;
154     }
155
156     public String JavaDoc getKeyStorePassword() {
157         return this.keyStorePassword;
158     }
159
160     public int getKeyStoreSize() throws KeyStoreException JavaDoc {
161         return this.keystore.size();
162     }
163
164     public KeyEntryInfo getKeyEntryInfo(String JavaDoc alias) throws KeyStoreException JavaDoc {
165         KeyEntryInfo info = null;
166
167         if (this.keystore.isCertificateEntry(alias)) {
168             // certificate entry
169
info = new KeyEntryInfo(alias, "trusted certificate", keystore
170                     .getCreationDate(alias));
171         } else if (this.keystore.isKeyEntry(alias)) {
172             // private key entry
173
info = new KeyEntryInfo(alias, "private key", keystore
174                     .getCreationDate(alias));
175         } else {
176             throw new KeyStoreException JavaDoc("invalid key entry type");
177         }
178         return info;
179     }
180
181     public List JavaDoc getKeyStoreEntries() throws KeyStoreException JavaDoc {
182         List JavaDoc list = new ArrayList JavaDoc();
183
184         Enumeration JavaDoc aliases = this.keystore.aliases();
185
186         while (aliases.hasMoreElements()) {
187             String JavaDoc alias = (String JavaDoc) aliases.nextElement();
188             list.add(getKeyEntryInfo(alias));
189         }
190         return list;
191     }
192
193     public Certificate JavaDoc[] getCertificateChain(String JavaDoc alias)
194             throws KeyStoreException JavaDoc {
195         Certificate JavaDoc[] certs = null;
196
197         if (keystore.isCertificateEntry(alias)) {
198             Certificate JavaDoc cert = keystore.getCertificate(alias);
199             certs = new Certificate JavaDoc[1];
200             certs[0] = cert;
201         } else if (keystore.isKeyEntry(alias)) {
202             certs = keystore.getCertificateChain(alias);
203         } else if (keystore.containsAlias(alias)) {
204             throw new KeyStoreException JavaDoc("Unsupported key-store-entry, alias = "
205                     + alias);
206         } else {
207             throw new KeyStoreException JavaDoc(
208                     "Key-store-entry alias not found, alias = " + alias);
209         }
210
211         return certs;
212     }
213
214     public String JavaDoc generateCSR(String JavaDoc alias) throws Exception JavaDoc {
215
216         // find certificate by alias
217
X509Certificate JavaDoc cert = (X509Certificate JavaDoc) keystore.getCertificate(alias);
218
219         // find private key by alias
220
PrivateKey JavaDoc key = (PrivateKey JavaDoc) keystore.getKey(alias, new String JavaDoc("")
221                 .toCharArray());
222
223         // generate csr
224
String JavaDoc csr = generateCSR(cert, key);
225         return csr;
226     }
227
228     public String JavaDoc generateCSR(X509Certificate JavaDoc cert, PrivateKey JavaDoc signingKey)
229             throws Exception JavaDoc {
230
231         String JavaDoc sigalg = cert.getSigAlgName();
232         X509Name subject = new X509Name(cert.getSubjectDN().toString());
233         PublicKey JavaDoc publicKey = cert.getPublicKey();
234         ASN1Set attributes = null;
235
236         PKCS10CertificationRequest csr = new PKCS10CertificationRequest(sigalg,
237                 subject, publicKey, attributes, signingKey);
238
239         if (!csr.verify()) {
240             throw new KeyStoreException JavaDoc("CSR verification failed");
241         }
242
243         ByteArrayOutputStream JavaDoc os = new ByteArrayOutputStream JavaDoc();
244         DEROutputStream deros = new DEROutputStream(os);
245         deros.writeObject(csr.getDERObject());
246         String JavaDoc b64 = new String JavaDoc(Base64.encode(os.toByteArray()));
247
248         final String JavaDoc BEGIN_CERT_REQ = "-----BEGIN CERTIFICATE REQUEST-----";
249         final String JavaDoc END_CERT_REQ = "-----END CERTIFICATE REQUEST-----";
250         final int CERT_REQ_LINE_LENGTH = 70;
251
252         StringBuffer JavaDoc sbuf = new StringBuffer JavaDoc(BEGIN_CERT_REQ).append('\n');
253
254         int idx = 0;
255         while (idx < b64.length()) {
256
257             int len = (idx + CERT_REQ_LINE_LENGTH > b64.length()) ? b64
258                     .length()
259                     - idx : CERT_REQ_LINE_LENGTH;
260
261             String JavaDoc chunk = b64.substring(idx, idx + len);
262
263             sbuf.append(chunk).append('\n');
264             idx += len;
265         }
266
267         sbuf.append(END_CERT_REQ);
268         return sbuf.toString();
269     }
270
271     public void generateKeyPair(String JavaDoc alias, String JavaDoc keyalg, Integer JavaDoc keysize,
272             String JavaDoc sigalg, Integer JavaDoc validity, String JavaDoc cn, String JavaDoc ou, String JavaDoc o,
273             String JavaDoc l, String JavaDoc st, String JavaDoc c)
274             throws java.security.NoSuchAlgorithmException JavaDoc,
275             java.security.KeyStoreException JavaDoc, java.security.SignatureException JavaDoc,
276             java.security.InvalidKeyException JavaDoc,
277             java.security.cert.CertificateException JavaDoc, java.io.IOException JavaDoc {
278
279         KeyPairGenerator JavaDoc kpgen = KeyPairGenerator.getInstance(keyalg);
280
281         kpgen.initialize(keysize.intValue());
282
283         KeyPair JavaDoc keyPair = kpgen.generateKeyPair();
284
285         X509Certificate JavaDoc cert = generateCert(keyPair.getPublic(), keyPair
286                 .getPrivate(), sigalg, validity.intValue(), cn, ou, o, l, st, c);
287
288         keystore.setKeyEntry(alias, keyPair.getPrivate(), new String JavaDoc()
289                 .toCharArray(), new Certificate JavaDoc[] { cert });
290
291         saveKeyStore();
292     }
293
294     public void saveKeyStore() throws java.io.IOException JavaDoc,
295             java.security.KeyStoreException JavaDoc,
296             java.security.cert.CertificateException JavaDoc,
297             java.security.NoSuchAlgorithmException JavaDoc {
298
299         FileOutputStream JavaDoc os = null;
300
301         try {
302             File JavaDoc keyStore = serverInfo.resolveServer(this.keyStoreLocation);
303             os = new FileOutputStream JavaDoc(keyStore);
304
305             keystore.store(os, keyStorePassword.toCharArray());
306         } finally {
307             if (os != null) {
308                 try {
309                     os.close();
310                 } catch (Exception JavaDoc ex) {
311                 }
312             }
313         }
314     }
315
316     public X509Certificate JavaDoc generateCert(PublicKey JavaDoc publicKey,
317             PrivateKey JavaDoc privateKey, String JavaDoc sigalg, int validity, String JavaDoc cn,
318             String JavaDoc ou, String JavaDoc o, String JavaDoc l, String JavaDoc st, String JavaDoc c)
319             throws java.security.SignatureException JavaDoc,
320             java.security.InvalidKeyException JavaDoc {
321         X509V1CertificateGenerator certgen = new X509V1CertificateGenerator();
322
323         // issuer dn
324
Vector JavaDoc order = new Vector JavaDoc();
325         Hashtable JavaDoc attrmap = new Hashtable JavaDoc();
326
327         if (cn != null) {
328             attrmap.put(X509Principal.CN, cn);
329             order.add(X509Principal.CN);
330         }
331
332         if (ou != null) {
333             attrmap.put(X509Principal.OU, ou);
334             order.add(X509Principal.OU);
335         }
336
337         if (o != null) {
338             attrmap.put(X509Principal.O, o);
339             order.add(X509Principal.O);
340         }
341
342         if (l != null) {
343             attrmap.put(X509Principal.L, l);
344             order.add(X509Principal.L);
345         }
346
347         if (st != null) {
348             attrmap.put(X509Principal.ST, st);
349             order.add(X509Principal.ST);
350         }
351
352         if (c != null) {
353             attrmap.put(X509Principal.C, c);
354             order.add(X509Principal.C);
355         }
356
357         X509Principal issuerDN = new X509Principal(order, attrmap);
358         certgen.setIssuerDN(issuerDN);
359
360         // validity
361
long curr = System.currentTimeMillis();
362         long untill = curr + (long) validity * 24 * 60 * 60 * 1000;
363
364         certgen.setNotBefore(new Date JavaDoc(curr));
365         certgen.setNotAfter(new Date JavaDoc(untill));
366
367         // subject dn
368
certgen.setSubjectDN(issuerDN);
369
370         // public key
371
certgen.setPublicKey(publicKey);
372
373         // signature alg
374
certgen.setSignatureAlgorithm(sigalg);
375
376         // serial number
377
certgen.setSerialNumber(new BigInteger JavaDoc(String.valueOf(curr)));
378
379         // make certificate
380
X509Certificate JavaDoc cert = certgen.generateX509Certificate(privateKey);
381         return cert;
382     }
383
384     public void importTrustedX509Certificate(String JavaDoc alias, String JavaDoc certfile)
385             throws java.io.FileNotFoundException JavaDoc,
386             java.security.cert.CertificateException JavaDoc,
387             java.security.KeyStoreException JavaDoc, java.io.IOException JavaDoc,
388             java.security.NoSuchAlgorithmException JavaDoc,
389             java.security.NoSuchProviderException JavaDoc {
390         InputStream JavaDoc is = null;
391
392         try {
393             CertificateFactory JavaDoc cf = CertificateFactory.getInstance("X.509",
394                     keyStoreProvider);
395
396             is = new FileInputStream JavaDoc(certfile);
397             Certificate JavaDoc cert = cf.generateCertificate(is);
398
399             keystore.setCertificateEntry(alias, cert);
400
401             saveKeyStore();
402         } finally {
403             if (is != null) {
404                 try {
405                     is.close();
406                 } catch (Exception JavaDoc e) {
407                 }
408             }
409         }
410     }
411
412     public void importPKCS7Certificate(String JavaDoc alias, String JavaDoc certbuf)
413             throws java.security.cert.CertificateException JavaDoc,
414             java.security.NoSuchProviderException JavaDoc,
415             java.security.KeyStoreException JavaDoc,
416             java.security.NoSuchAlgorithmException JavaDoc,
417             java.security.UnrecoverableKeyException JavaDoc, java.io.IOException JavaDoc {
418
419         InputStream JavaDoc is = null;
420
421         try {
422             is = new ByteArrayInputStream JavaDoc(certbuf.getBytes());
423             importPKCS7Certificate(alias, is);
424         } finally {
425             if (is != null) {
426                 try {
427                     is.close();
428                 } catch (Exception JavaDoc e) {
429                 }
430             }
431         }
432     }
433
434     public void importPKCS7Certificate(String JavaDoc alias, InputStream JavaDoc is)
435             throws java.security.cert.CertificateException JavaDoc,
436             java.security.NoSuchProviderException JavaDoc,
437             java.security.KeyStoreException JavaDoc,
438             java.security.NoSuchAlgorithmException JavaDoc,
439             java.security.UnrecoverableKeyException JavaDoc, java.io.IOException JavaDoc {
440
441         CertificateFactory JavaDoc cf = CertificateFactory.getInstance("X.509",
442                 keyStoreProvider);
443         Collection JavaDoc certcoll = cf.generateCertificates(is);
444
445         Certificate JavaDoc[] chain = new Certificate JavaDoc[certcoll.size()];
446
447         Iterator JavaDoc iter = certcoll.iterator();
448         for (int i = 0; iter.hasNext(); i++) {
449             chain[i] = (Certificate JavaDoc) iter.next();
450         }
451
452         char[] password = keyPassword.toCharArray();
453         keystore.setKeyEntry(alias, keystore.getKey(alias, password), password,
454                 chain);
455
456         saveKeyStore();
457     }
458
459
460     public static final GBeanInfo GBEAN_INFO;
461
462     static {
463         GBeanInfoBuilder infoFactory = GBeanInfoBuilder.createStatic(KeyStoreGBean.class);
464
465         infoFactory.addAttribute("keyStoreType", String JavaDoc.class, true);
466         infoFactory.addAttribute("keyStoreProvider", String JavaDoc.class, true);
467         infoFactory.addAttribute("keyStoreLocation", String JavaDoc.class, true);
468         infoFactory.addAttribute("keyStorePassword", String JavaDoc.class, true);
469
470         infoFactory.addReference("serverInfo", ServerInfo.class, NameFactory.GERONIMO_SERVICE);
471
472         infoFactory.addOperation("getKeyEntryInfo",
473                 new Class JavaDoc[] { String JavaDoc.class });
474         infoFactory.addOperation("getKeyStoreSize");
475         infoFactory.addOperation("getKeyStoreEntries");
476         infoFactory.addOperation("getCertificateChain",
477                 new Class JavaDoc[] { String JavaDoc.class });
478         infoFactory.addOperation("generateCSR", new Class JavaDoc[] { String JavaDoc.class });
479
480         infoFactory.addOperation("generateKeyPair", new Class JavaDoc[] { String JavaDoc.class,
481                 String JavaDoc.class, Integer JavaDoc.class, String JavaDoc.class, Integer JavaDoc.class,
482                 String JavaDoc.class, String JavaDoc.class, String JavaDoc.class, String JavaDoc.class,
483                 String JavaDoc.class, String JavaDoc.class });
484
485         infoFactory.addOperation("importTrustedX509Certificate", new Class JavaDoc[] {
486                 String JavaDoc.class, String JavaDoc.class });
487         infoFactory.addOperation("importPKCS7Certificate", new Class JavaDoc[] {
488                 String JavaDoc.class, String JavaDoc.class });
489
490         GBEAN_INFO = infoFactory.getBeanInfo();
491     }
492
493     public static GBeanInfo getGBeanInfo() {
494         return GBEAN_INFO;
495     }
496
497 }
498
Popular Tags