KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > base > util > KeyStoreUtil


1 /*
2  * $Id: KeyStoreUtil.java 6990 2006-03-14 03:52:35Z jonesde $
3  *
4  * Copyright (c) 2003 The Open For Business Project - www.ofbiz.org
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included
14  * in all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
21  * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
22  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  *
24  */

25 package org.ofbiz.base.util;
26
27 import java.io.*;
28 import java.security.AlgorithmParameterGenerator JavaDoc;
29 import java.security.AlgorithmParameters JavaDoc;
30 import java.security.GeneralSecurityException JavaDoc;
31 import java.security.Key JavaDoc;
32 import java.security.KeyFactory JavaDoc;
33 import java.security.KeyPair JavaDoc;
34 import java.security.KeyPairGenerator JavaDoc;
35 import java.security.KeyStore JavaDoc;
36 import java.security.KeyStoreException JavaDoc;
37 import java.security.NoSuchAlgorithmException JavaDoc;
38 import java.security.PrivateKey JavaDoc;
39 import java.security.PublicKey JavaDoc;
40 import java.security.UnrecoverableKeyException JavaDoc;
41 import java.security.cert.Certificate JavaDoc;
42 import java.security.cert.CertificateEncodingException JavaDoc;
43 import java.security.cert.CertificateException JavaDoc;
44 import java.security.cert.CertificateFactory JavaDoc;
45 import java.security.spec.InvalidKeySpecException JavaDoc;
46 import java.security.spec.PKCS8EncodedKeySpec JavaDoc;
47 import java.security.spec.X509EncodedKeySpec JavaDoc;
48 import java.util.Collection JavaDoc;
49
50 import javax.crypto.KeyAgreement;
51 import javax.crypto.SecretKey;
52 import javax.crypto.spec.DHParameterSpec;
53
54 /**
55  * KeyStoreUtil - Utilities for getting KeyManagers and TrustManagers
56  *
57  * @author <a HREF="mailto:jaz@ofbiz.org">Andy Zeneski</a>
58  * @version $Rev: 6990 $
59  * @since 3.0
60  */

61 public class KeyStoreUtil {
62
63     public static final String JavaDoc module = KeyStoreUtil.class.getName();
64
65     public static String JavaDoc getKeyStoreFileName() {
66         return UtilProperties.getPropertyValue("jsse.properties", "ofbiz.client.keyStore", null);
67     }
68
69     public static String JavaDoc getKeyStorePassword() {
70         return UtilProperties.getPropertyValue("jsse.properties", "ofbiz.client.keyStore.password", null);
71     }
72
73     public static String JavaDoc getKeyStoreType() {
74         return UtilProperties.getPropertyValue("jsse.properties", "ofbiz.client.keyStore.type", "jks");
75     }
76
77     public static String JavaDoc getTrustStoreFileName() {
78         return UtilProperties.getPropertyValue("jsse.properties", "ofbiz.trustStore", null);
79     }
80
81     public static String JavaDoc getTrustStorePassword() {
82         return UtilProperties.getPropertyValue("jsse.properties", "ofbiz.trustStore.password", null);
83     }
84
85     public static String JavaDoc getTrustStoreType() {
86         return UtilProperties.getPropertyValue("jsse.properties", "ofbiz.trustStore.type", "jks");
87     }
88
89     public static KeyStore JavaDoc getKeyStore() throws IOException, GeneralSecurityException JavaDoc {
90         if (getKeyStoreFileName() != null && !keyStoreExists(getKeyStoreFileName())) {
91             return null;
92         }
93         FileInputStream fis = new FileInputStream(getKeyStoreFileName());
94         KeyStore JavaDoc ks = KeyStore.getInstance(getKeyStoreType());
95         ks.load(fis, getKeyStorePassword().toCharArray());
96         fis.close();
97         return ks;
98     }
99
100     public static void saveKeyStore(KeyStore JavaDoc ks) throws IOException, KeyStoreException JavaDoc, NoSuchAlgorithmException JavaDoc, CertificateException JavaDoc {
101         ks.store(new FileOutputStream(getKeyStoreFileName()), getKeyStorePassword().toCharArray());
102     }
103
104     public static KeyStore JavaDoc getTrustStore() throws IOException, GeneralSecurityException JavaDoc {
105         if (getTrustStoreFileName() != null && !keyStoreExists(getTrustStoreFileName())) {
106             return null;
107         }
108         FileInputStream fis = new FileInputStream(getTrustStoreFileName());
109         KeyStore JavaDoc ks = KeyStore.getInstance(getTrustStoreType());
110         ks.load(fis, getTrustStorePassword().toCharArray());
111         fis.close();
112         return ks;
113     }
114
115     public static void saveTrustStore(KeyStore JavaDoc ks) throws IOException, KeyStoreException JavaDoc, NoSuchAlgorithmException JavaDoc, CertificateException JavaDoc {
116         ks.store(new FileOutputStream(getTrustStoreFileName()), getTrustStorePassword().toCharArray());
117     }
118
119     public static boolean keyStoreExists(String JavaDoc fileName) {
120         File keyFile = new File(fileName);
121         return keyFile.exists();
122     }
123
124     public static KeyStore JavaDoc createKeyStore(String JavaDoc fileName, String JavaDoc password) throws KeyStoreException JavaDoc, NoSuchAlgorithmException JavaDoc, CertificateException JavaDoc, IOException {
125         KeyStore JavaDoc ks = null;
126         ks = KeyStore.getInstance("jks");
127         ks.load(null, password.toCharArray());
128         ks.store(new FileOutputStream(fileName), password.toCharArray());
129         ks.load(new FileInputStream(fileName), password.toCharArray());
130         return ks;
131     }
132
133     public static void renameKeyStoreEntry(String JavaDoc fromAlias, String JavaDoc toAlias) throws GeneralSecurityException JavaDoc, IOException {
134         KeyStore JavaDoc ks = getKeyStore();
135         String JavaDoc pass = getKeyStorePassword();
136         renameEntry(ks, pass, fromAlias, toAlias);
137         saveKeyStore(ks);
138     }
139
140     private static void renameEntry(KeyStore JavaDoc ks, String JavaDoc pass, String JavaDoc fromAlias, String JavaDoc toAlias) throws KeyStoreException JavaDoc, UnrecoverableKeyException JavaDoc, NoSuchAlgorithmException JavaDoc {
141         if (ks.isKeyEntry(fromAlias)) {
142             Key JavaDoc fromKey = ks.getKey(fromAlias, pass.toCharArray());
143             if (fromKey instanceof PrivateKey JavaDoc) {
144                 Certificate JavaDoc[] certs = ks.getCertificateChain(fromAlias);
145                 ks.deleteEntry(fromAlias);
146                 ks.setKeyEntry(toAlias, fromKey, pass.toCharArray(), certs);
147             }
148         } else if (ks.isCertificateEntry(fromAlias)) {
149             Certificate JavaDoc cert = ks.getCertificate(fromAlias);
150             ks.deleteEntry(fromAlias);
151             ks.setCertificateEntry(toAlias, cert);
152         }
153     }
154
155     public static void importPKCS8CertChain(KeyStore JavaDoc ks, String JavaDoc alias, byte[] keyBytes, String JavaDoc keyPass, byte[] certChain) throws InvalidKeySpecException JavaDoc, NoSuchAlgorithmException JavaDoc, CertificateException JavaDoc, KeyStoreException JavaDoc {
156         // load the private key
157
KeyFactory JavaDoc kf = KeyFactory.getInstance("RSA");
158         PKCS8EncodedKeySpec JavaDoc keysp = new PKCS8EncodedKeySpec JavaDoc(keyBytes);
159         PrivateKey JavaDoc pk = kf.generatePrivate(keysp);
160
161         // load the cert chain
162
CertificateFactory JavaDoc cf = CertificateFactory.getInstance("X.509");
163         ByteArrayInputStream bais = new ByteArrayInputStream(certChain);
164
165         Collection JavaDoc certCol = cf.generateCertificates(bais);
166         Certificate JavaDoc[] certs = new Certificate JavaDoc[certCol.toArray().length];
167         if (certCol.size() == 1) {
168             Debug.log("Single certificate; no chain", module);
169             bais = new ByteArrayInputStream(certChain);
170             Certificate JavaDoc cert = cf.generateCertificate(bais);
171             certs[0] = cert;
172         } else {
173             Debug.log("Certificate chain length : " + certCol.size(), module);
174             certs = (Certificate JavaDoc[]) certCol.toArray();
175         }
176
177         ks.setKeyEntry(alias, pk, keyPass.toCharArray(), certs);
178     }
179
180     // key pair generation methods
181
public static KeyPair JavaDoc createDHKeyPair() throws Exception JavaDoc {
182         AlgorithmParameterGenerator JavaDoc apGen = AlgorithmParameterGenerator.getInstance("DH");
183         apGen.init(1024);
184
185         AlgorithmParameters JavaDoc algParams = apGen.generateParameters();
186         DHParameterSpec dhParamSpec = (DHParameterSpec) algParams.getParameterSpec(DHParameterSpec.class);
187
188         KeyPairGenerator JavaDoc keyGen = KeyPairGenerator.getInstance("DH");
189         keyGen.initialize(dhParamSpec);
190
191         KeyPair JavaDoc keypair = keyGen.generateKeyPair();
192         return keypair;
193     }
194
195     public static KeyPair JavaDoc getKeyPair(String JavaDoc alias, String JavaDoc password) throws Exception JavaDoc {
196         KeyStore JavaDoc ks = getKeyStore();
197         Key JavaDoc key = ks.getKey(alias, password.toCharArray());
198         if (key instanceof PrivateKey JavaDoc) {
199             Certificate JavaDoc cert = ks.getCertificate(alias);
200             PublicKey JavaDoc publicKey = cert.getPublicKey();
201             return new KeyPair JavaDoc(publicKey, (PrivateKey JavaDoc) key);
202         } else {
203             Debug.logError("Key is not an instance of PrivateKey", module);
204         }
205         return null;
206     }
207
208     public static void storeCertificate(String JavaDoc alias, Certificate JavaDoc cert) throws Exception JavaDoc {
209         KeyStore JavaDoc ks = getKeyStore();
210         ks.setCertificateEntry(alias, cert);
211         ks.store(new FileOutputStream(getKeyStoreFileName()), getKeyStorePassword().toCharArray());
212     }
213
214     public static void storeKeyPair(KeyPair JavaDoc keyPair, String JavaDoc alias, String JavaDoc password) throws Exception JavaDoc {
215         KeyStore JavaDoc ks = getKeyStore();
216         CertificateFactory JavaDoc cf = CertificateFactory.getInstance("X.509");
217         PrivateKey JavaDoc privateKey = keyPair.getPrivate();
218         PublicKey JavaDoc publicKey = keyPair.getPublic();
219         // not sure what to do here. Do we need to create a cert to assoc with the private key?
220
// cannot find methods for just setting the private/public key; missing something
221
ks.store(new FileOutputStream(getKeyStoreFileName()), getKeyStorePassword().toCharArray());
222     }
223
224     public static String JavaDoc certToString(Certificate JavaDoc cert) throws CertificateEncodingException JavaDoc {
225         byte[] certBuf = cert.getEncoded();
226         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
227         buf.append("-----BEGIN CERTIFICATE-----\n");
228         buf.append(Base64.base64Encode(certBuf));
229         buf.append("\n-----END CERTIFICATE-----\n");
230         return buf.toString();
231     }
232
233     public static Certificate JavaDoc pemToCert(String JavaDoc certString) throws IOException, CertificateException JavaDoc {
234         return pemToCert(new StringReader(certString));
235     }
236
237     public static Certificate JavaDoc pemToCert(File certFile) throws IOException, CertificateException JavaDoc {
238         return pemToCert(new FileInputStream(certFile));
239     }
240
241     public static Certificate JavaDoc pemToCert(InputStream is) throws IOException, CertificateException JavaDoc {
242         return pemToCert(new InputStreamReader(is));
243     }
244
245     public static Certificate JavaDoc pemToCert(Reader r) throws IOException, CertificateException JavaDoc {
246         String JavaDoc header = "-----BEGIN CERTIFICATE-----";
247         String JavaDoc footer = "-----END CERTIFICATE-----";
248
249         BufferedReader reader = new BufferedReader(r);
250         ByteArrayOutputStream baos = new ByteArrayOutputStream();
251         PrintStream ps = new PrintStream(baos);
252
253         String JavaDoc line;
254
255         // ignore up to the header
256
while ((line = reader.readLine()) != null && !line.equals(header)) {
257             continue;
258         }
259
260         // no header found
261
if (line == null) {
262             throw new IOException("Error reading certificate, missing BEGIN boundary");
263         }
264
265         // in between the header and footer is the actual certificate
266
while ((line = reader.readLine()) != null && !line.equals(footer)) {
267             ps.print(line);
268         }
269
270         // no footer found
271
if (line == null) {
272             throw new IOException("Error reading certificate, missing END boundary");
273         }
274         ps.close();
275
276         // decode the buffer to a X509Certificate
277

278         CertificateFactory JavaDoc cf = CertificateFactory.getInstance("X.509");
279         byte[] certBytes = Base64.base64Decode(baos.toByteArray());
280         return cf.generateCertificate(new ByteArrayInputStream(certBytes));
281     }
282
283     public static SecretKey generateSecretKey(PrivateKey JavaDoc ourKey, PublicKey JavaDoc theirKey) throws Exception JavaDoc {
284         KeyAgreement ka = KeyAgreement.getInstance("DH");
285         ka.init(ourKey);
286         ka.doPhase(theirKey, true);
287         return ka.generateSecret("TripleDES");
288     }
289
290     public static PublicKey JavaDoc readDHPublicKey(byte[] keyBytes) throws NoSuchAlgorithmException JavaDoc, InvalidKeySpecException JavaDoc {
291         X509EncodedKeySpec JavaDoc x509KeySpec = new X509EncodedKeySpec JavaDoc(keyBytes);
292         KeyFactory JavaDoc keyFactory = KeyFactory.getInstance("DH");
293         return keyFactory.generatePublic(x509KeySpec);
294     }
295
296     public static PrivateKey JavaDoc readDHPrivateKey(byte[] keyBytes) throws NoSuchAlgorithmException JavaDoc, InvalidKeySpecException JavaDoc {
297         X509EncodedKeySpec JavaDoc x509KeySpec = new X509EncodedKeySpec JavaDoc(keyBytes);
298         KeyFactory JavaDoc keyFactory = KeyFactory.getInstance("DH");
299         return keyFactory.generatePrivate(x509KeySpec);
300     }
301
302 }
303
Popular Tags