KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > servicemix > jbi > security > keystore > impl > FileKeystoreInstance


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 package org.apache.servicemix.jbi.security.keystore.impl;
18
19 import java.io.BufferedInputStream JavaDoc;
20 import java.io.File JavaDoc;
21 import java.io.FileInputStream JavaDoc;
22 import java.io.IOException JavaDoc;
23 import java.io.InputStream JavaDoc;
24 import java.security.Key JavaDoc;
25 import java.security.KeyStore JavaDoc;
26 import java.security.KeyStoreException JavaDoc;
27 import java.security.NoSuchAlgorithmException JavaDoc;
28 import java.security.PrivateKey JavaDoc;
29 import java.security.UnrecoverableKeyException JavaDoc;
30 import java.security.cert.Certificate JavaDoc;
31 import java.security.cert.CertificateException JavaDoc;
32 import java.util.ArrayList JavaDoc;
33 import java.util.Enumeration JavaDoc;
34 import java.util.HashMap JavaDoc;
35 import java.util.List JavaDoc;
36 import java.util.Map JavaDoc;
37
38 import javax.net.ssl.KeyManager;
39 import javax.net.ssl.KeyManagerFactory;
40 import javax.net.ssl.TrustManager;
41 import javax.net.ssl.TrustManagerFactory;
42
43 import org.apache.commons.logging.Log;
44 import org.apache.commons.logging.LogFactory;
45 import org.apache.servicemix.jbi.security.keystore.KeystoreInstance;
46 import org.apache.servicemix.jbi.security.keystore.KeystoreIsLocked;
47 import org.springframework.core.io.Resource;
48
49 /**
50  *
51  * @org.apache.xbean.XBean element="keystore"
52  */

53 public class FileKeystoreInstance implements KeystoreInstance {
54
55     private static final Log log = LogFactory.getLog(FileKeystoreInstance.class);
56     private final static String JavaDoc JKS = "JKS";
57     
58     private Resource path;
59     private String JavaDoc name;
60     private String JavaDoc keystorePassword;
61     private Map JavaDoc keyPasswords = new HashMap JavaDoc();
62     private File JavaDoc keystoreFile; // Only valid after startup
63

64     // The following variables are the state of the keystore, which should be chucked if the file on disk changes
65
private List JavaDoc privateKeys = new ArrayList JavaDoc();
66     private List JavaDoc trustCerts = new ArrayList JavaDoc();
67     private KeyStore JavaDoc keystore;
68     private long keystoreReadDate = Long.MIN_VALUE;
69     
70     /**
71      * @param keyPasswords the keyPasswords to set
72      */

73     public void setKeyPasswords(String JavaDoc keyPasswords) {
74         if (keyPasswords != null) {
75             String JavaDoc[] keys = keyPasswords.split("\\]\\!\\[");
76             for (int i = 0; i < keys.length; i++) {
77                 String JavaDoc key = keys[i];
78                 int pos = key.indexOf('=');
79                 this.keyPasswords.put(key.substring(0, pos), key.substring(pos+1).toCharArray());
80             }
81         }
82     }
83
84     /**
85      * @return the keystoreName
86      */

87     public String JavaDoc getName() {
88         return name;
89     }
90
91     /**
92      * @param keystoreName the keystoreName to set
93      */

94     public void setName(String JavaDoc keystoreName) {
95         this.name = keystoreName;
96     }
97
98     /**
99      * @param keystorePassword the keystorePassword to set
100      */

101     public void setKeystorePassword(String JavaDoc keystorePassword) {
102         this.keystorePassword = keystorePassword;
103     }
104
105     /**
106      * @return the keystorePath
107      */

108     public Resource getPath() {
109         return path;
110     }
111
112     /**
113      * @param keystorePath the keystorePath to set
114      */

115     public void setPath(Resource keystorePath) throws IOException JavaDoc {
116         this.path = keystorePath;
117         this.keystoreFile = keystorePath.getFile();
118     }
119
120     public Certificate JavaDoc getCertificate(String JavaDoc alias) {
121         if (!loadKeystoreData()) {
122             return null;
123         }
124         try {
125             return keystore.getCertificate(alias);
126         } catch (KeyStoreException JavaDoc e) {
127             log.error("Unable to read certificate from keystore", e);
128         }
129         return null;
130     }
131
132     public String JavaDoc getCertificateAlias(Certificate JavaDoc cert) {
133         if (!loadKeystoreData()) {
134             return null;
135         }
136         try {
137             return keystore.getCertificateAlias(cert);
138         } catch (KeyStoreException JavaDoc e) {
139             log.error("Unable to read retrieve alias for given certificate from keystore", e);
140         }
141         return null;
142     }
143
144     public Certificate JavaDoc[] getCertificateChain(String JavaDoc alias) {
145         if (!loadKeystoreData()) {
146             return null;
147         }
148         try {
149             return keystore.getCertificateChain(alias);
150         } catch (KeyStoreException JavaDoc e) {
151             log.error("Unable to read certificate chain from keystore", e);
152         }
153         return null;
154     }
155
156     public KeyManager[] getKeyManager(String JavaDoc algorithm, String JavaDoc keyAlias) throws KeystoreIsLocked, NoSuchAlgorithmException JavaDoc, KeyStoreException JavaDoc, UnrecoverableKeyException JavaDoc {
157         if(isKeystoreLocked()) {
158             throw new KeystoreIsLocked("Keystore '"+name+"' is locked; please unlock it in the console.");
159         }
160         if(keystore == null || keystoreReadDate < keystoreFile.lastModified()) {
161             loadKeystoreData();
162         }
163         KeyManagerFactory keyFactory = KeyManagerFactory.getInstance(algorithm);
164         keyFactory.init(keystore, (char[]) keyPasswords.get(keyAlias));
165         return keyFactory.getKeyManagers();
166     }
167
168     public PrivateKey JavaDoc getPrivateKey(String JavaDoc alias) {
169         if (!loadKeystoreData()) {
170             return null;
171         }
172         try {
173             if (isKeyLocked(alias)) {
174                 return null;
175             }
176             Key JavaDoc key = keystore.getKey(alias, (char[]) keyPasswords.get(alias));
177             if (key instanceof PrivateKey JavaDoc) {
178                 return (PrivateKey JavaDoc) key;
179             }
180         } catch (KeyStoreException JavaDoc e) {
181             log.error("Unable to read private key from keystore", e);
182         } catch (NoSuchAlgorithmException JavaDoc e) {
183             log.error("Unable to read private key from keystore", e);
184         } catch (UnrecoverableKeyException JavaDoc e) {
185             log.error("Unable to read private key from keystore", e);
186         }
187         return null;
188     }
189
190     public TrustManager[] getTrustManager(String JavaDoc algorithm) throws KeyStoreException JavaDoc, NoSuchAlgorithmException JavaDoc, KeystoreIsLocked {
191         if(isKeystoreLocked()) {
192             throw new KeystoreIsLocked("Keystore '"+name+"' is locked; please unlock it in the console.");
193         }
194         if (!loadKeystoreData()) {
195             return null;
196         }
197         TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(algorithm);
198         trustFactory.init(keystore);
199         return trustFactory.getTrustManagers();
200     }
201
202     public boolean isKeyLocked(String JavaDoc keyAlias) {
203         return keyPasswords.get(keyAlias) == null;
204     }
205
206     public boolean isKeystoreLocked() {
207         return keystorePassword == null;
208     }
209
210     public String JavaDoc[] listPrivateKeys() {
211         if (!loadKeystoreData()) {
212             return null;
213         }
214         return (String JavaDoc[]) privateKeys.toArray(new String JavaDoc[privateKeys.size()]);
215     }
216
217     public String JavaDoc[] listTrustCertificates() {
218         if (!loadKeystoreData()) {
219             return null;
220         }
221         return (String JavaDoc[]) trustCerts.toArray(new String JavaDoc[trustCerts.size()]);
222     }
223
224     // ==================== Internals =====================
225

226     private boolean loadKeystoreData() {
227         if (keystoreFile == null) {
228             throw new IllegalArgumentException JavaDoc("keystorePath not set");
229         }
230         if (keystoreReadDate >= keystoreFile.lastModified()) {
231             return true;
232         }
233         if (!keystoreFile.exists() || !keystoreFile.canRead()) {
234             throw new IllegalArgumentException JavaDoc("Invalid keystore file (" + path + " = " + keystoreFile.getAbsolutePath() + ")");
235         }
236         try {
237             keystoreReadDate = System.currentTimeMillis();
238             privateKeys.clear();
239             trustCerts.clear();
240             if(keystore == null) {
241                 keystore = KeyStore.getInstance(JKS);
242             }
243             InputStream JavaDoc in = new BufferedInputStream JavaDoc(new FileInputStream JavaDoc(keystoreFile));
244             keystore.load(in, keystorePassword == null ? new char[0] : keystorePassword.toCharArray());
245             in.close();
246             Enumeration JavaDoc aliases = keystore.aliases();
247             while (aliases.hasMoreElements()) {
248                 String JavaDoc alias = (String JavaDoc) aliases.nextElement();
249                 if (keystore.isKeyEntry(alias)) {
250                     privateKeys.add(alias);
251                 } else if (keystore.isCertificateEntry(alias)) {
252                     trustCerts.add(alias);
253                 }
254             }
255             return true;
256         } catch (KeyStoreException JavaDoc e) {
257             log.error("Unable to open keystore with provided password", e);
258         } catch (IOException JavaDoc e) {
259             log.error("Unable to open keystore with provided password", e);
260         } catch (NoSuchAlgorithmException JavaDoc e) {
261             log.error("Unable to open keystore with provided password", e);
262         } catch (CertificateException JavaDoc e) {
263             log.error("Unable to open keystore with provided password", e);
264         }
265         return false;
266     }
267
268 }
269
Popular Tags