Removed a bunch of dependencies on sun-proprietary classes.
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / utils / ExtKeyTool.java
1 /*
2  * The Shibboleth License, Version 1. Copyright (c) 2002 University Corporation for Advanced Internet Development, Inc.
3  * All rights reserved Redistribution and use in source and binary forms, with or without modification, are permitted
4  * provided that the following conditions are met: Redistributions of source code must retain the above copyright
5  * notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above
6  * copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials
7  * provided with the distribution, if any, must include the following acknowledgment: "This product includes software
8  * developed by the University Corporation for Advanced Internet Development <http://www.ucaid.edu>Internet2 Project.
9  * Alternately, this acknowledegement may appear in the software itself, if and wherever such third-party
10  * acknowledgments normally appear. Neither the name of Shibboleth nor the names of its contributors, nor Internet2, nor
11  * the University Corporation for Advanced Internet Development, Inc., nor UCAID may be used to endorse or promote
12  * products derived from this software without specific prior written permission. For written permission, please contact
13  * shibboleth@shibboleth.org Products derived from this software may not be called Shibboleth, Internet2, UCAID, or the
14  * University Corporation for Advanced Internet Development, nor may Shibboleth appear in their name, without prior
15  * written permission of the University Corporation for Advanced Internet Development. THIS SOFTWARE IS PROVIDED BY THE
16  * COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND WITH ALL FAULTS. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE
18  * DISCLAIMED AND THE ENTIRE RISK OF SATISFACTORY QUALITY, PERFORMANCE, ACCURACY, AND EFFORT IS WITH LICENSEE. IN NO
19  * EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY CORPORATION FOR ADVANCED INTERNET DEVELOPMENT, INC.
20  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
21  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
23  * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 package edu.internet2.middleware.shibboleth.utils;
27
28 import java.io.BufferedInputStream;
29 import java.io.BufferedReader;
30 import java.io.ByteArrayOutputStream;
31 import java.io.File;
32 import java.io.FileInputStream;
33 import java.io.FileNotFoundException;
34 import java.io.FileOutputStream;
35 import java.io.IOException;
36 import java.io.InputStream;
37 import java.io.InputStreamReader;
38 import java.io.PrintStream;
39 import java.security.Key;
40 import java.security.KeyFactory;
41 import java.security.KeyStore;
42 import java.security.KeyStoreException;
43 import java.security.NoSuchAlgorithmException;
44 import java.security.NoSuchProviderException;
45 import java.security.PrivateKey;
46 import java.security.Provider;
47 import java.security.PublicKey;
48 import java.security.Security;
49 import java.security.UnrecoverableKeyException;
50 import java.security.cert.CertificateException;
51 import java.security.cert.CertificateFactory;
52 import java.security.cert.X509Certificate;
53 import java.security.interfaces.RSAKey;
54 import java.security.spec.KeySpec;
55 import java.security.spec.PKCS8EncodedKeySpec;
56 import java.util.ArrayList;
57 import java.util.Collection;
58 import java.util.Properties;
59
60 import javax.crypto.Cipher;
61 import javax.crypto.SecretKey;
62 import javax.crypto.SecretKeyFactory;
63 import javax.crypto.spec.DESKeySpec;
64 import javax.crypto.spec.DESedeKeySpec;
65
66 import org.apache.log4j.ConsoleAppender;
67 import org.apache.log4j.Level;
68 import org.apache.log4j.LogManager;
69 import org.apache.log4j.Logger;
70 import org.apache.log4j.PatternLayout;
71 import org.bouncycastle.util.encoders.Base64;
72
73 /**
74  * Extension utility for use alongside Sun's keytool program. Performs useful functions not found in original.
75  * 
76  * @author Walter Hoehn
77  */
78
79 public class ExtKeyTool {
80
81         protected static Logger log = Logger.getLogger(ExtKeyTool.class.getName());
82
83         /**
84          * Creates and initializes a java <code>KeyStore</code>
85          * 
86          * @param provider
87          *            name of the jce provider to use in loading the keystore
88          * @param keyStoreStream
89          *            stream used to retrieve the keystore
90          * @param storeType
91          *            the type of the keystore
92          * @param keyStorePassword
93          *            password used to verify the integrity of the keystore
94          * @throws ExtKeyToolException
95          *             if a problem is encountered loading the keystore
96          */
97
98         protected KeyStore loadKeyStore(String provider, InputStream keyStoreStream, String storeType,
99                         char[] keyStorePassword) throws ExtKeyToolException {
100
101                 try {
102                         if (storeType == null) {
103                                 storeType = "JKS";
104                         }
105
106                         log.debug("Using keystore type: (" + storeType + ")");
107                         log.debug("Using provider: (" + provider + ")");
108
109                         KeyStore keyStore;
110                         if (storeType.equals("JKS")) {
111                                 keyStore = KeyStore.getInstance(storeType, "SUN");
112                         } else if (storeType.equals("JCEKS")) {
113                                 keyStore = KeyStore.getInstance(storeType, "SunJCE");
114                         } else {
115                                 keyStore = KeyStore.getInstance(storeType, provider);
116                         }
117
118                         if (keyStoreStream == null) {
119                                 log.error("Keystore must be specified.");
120                                 throw new ExtKeyToolException("Keystore must be specified.");
121                         }
122                         if (keyStorePassword == null) {
123                                 log.warn("No password given for keystore, integrity will not be verified.");
124                         }
125                         keyStore.load(keyStoreStream, keyStorePassword);
126
127                         return keyStore;
128
129                 } catch (KeyStoreException e) {
130                         log.error("Problem loading keystore: " + e);
131                         throw new ExtKeyToolException("Problem loading keystore: " + e);
132                 } catch (NoSuchProviderException e) {
133                         log.error("The specified provider is not available.");
134                         throw new ExtKeyToolException("The specified provider is not available.");
135                 } catch (CertificateException ce) {
136                         log.error("Could not open keystore: " + ce);
137                         throw new ExtKeyToolException("Could not open keystore: " + ce);
138                 } catch (IOException ioe) {
139                         log.error("Could not export key: " + ioe);
140                         throw new ExtKeyToolException("Could not export key: " + ioe);
141                 } catch (NoSuchAlgorithmException nse) {
142                         log.error("Could not open keystore with the installed JCE providers: " + nse);
143                         throw new ExtKeyToolException("Could not open keystore with the installed JCE providers: " + nse);
144                 }
145         }
146
147         /**
148          * Retrieves a private key from a java keystore and writes it to an <code>PrintStream</code>
149          * 
150          * @param provider
151          *            name of the jce provider to use in retrieving the key
152          * @param outStream
153          *            stream that should be used to output the retrieved key
154          * @param keyStoreStream
155          *            stream used to retrieve the keystore
156          * @param storeType
157          *            the type of the keystore
158          * @param keyStorePassword
159          *            password used to verify the integrity of the keystore
160          * @param keyAlias
161          *            the alias under which the key is stored
162          * @param keyPassword
163          *            the password for recovering the key
164          * @param rfc
165          *            boolean indicator of whether the key should be Base64 encoded before being written to the stream
166          * @throws ExtKeyToolException
167          *             if there a problem retrieving or writing the key
168          */
169
170         public void exportKey(String provider, PrintStream outStream, InputStream keyStoreStream, String storeType,
171                         char[] keyStorePassword, String keyAlias, char[] keyPassword, boolean rfc) throws ExtKeyToolException {
172
173                 try {
174
175                         KeyStore keyStore = loadKeyStore(provider, keyStoreStream, storeType, keyStorePassword);
176
177                         if (keyAlias == null) {
178                                 log.error("Key alias must be specified.");
179                                 throw new ExtKeyToolException("Key alias must be specified.");
180                         }
181                         log.info("Searching for key.");
182
183                         Key key = keyStore.getKey(keyAlias, keyPassword);
184                         if (key == null) {
185                                 log.error("Key not found in store.");
186                                 throw new ExtKeyToolException("Key not found in store.");
187                         }
188                         log.info("Found key.");
189
190                         if (rfc) {
191                                 log.debug("Dumping with rfc encoding");
192                                 outStream.println("-----BEGIN PRIVATE KEY-----");
193                                 outStream.println(Base64.encode(key.getEncoded()));
194
195                                 outStream.println("-----END PRIVATE KEY-----");
196                         } else {
197                                 log.debug("Dumping with default encoding.");
198                                 outStream.write(key.getEncoded());
199                         }
200
201                 } catch (KeyStoreException e) {
202                         log.error("Problem accessing keystore: " + e);
203                         throw new ExtKeyToolException("Problem loading keystore: " + e);
204                 } catch (IOException ioe) {
205                         log.error("Could not export key: " + ioe);
206                         throw new ExtKeyToolException("Could not export key: " + ioe);
207                 } catch (NoSuchAlgorithmException nse) {
208                         log.error("Could not recover key with the installed JCE providers: " + nse);
209                         throw new ExtKeyToolException("Could not recover key with the installed JCE providers: " + nse);
210                 } catch (UnrecoverableKeyException uke) {
211                         log.error("The key specified key cannot be recovered with the given password: " + uke);
212                         throw new ExtKeyToolException("The key specified key cannot be recovered with the given password: " + uke);
213                 }
214         }
215
216         /**
217          * Attempts to unmarshall a secret key from a given stream.
218          * 
219          * @param keyStream
220          *            the <code>InputStream</code> suppying the key
221          * @param algorithm
222          *            the key algorithm
223          * @throws ExtKeyToolException
224          *             if there a problem unmarshalling the key
225          */
226
227         protected SecretKey readSecretKey(String provider, InputStream keyStream, String algorithm)
228                         throws ExtKeyToolException {
229
230                 try {
231                         SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm, provider);
232
233                         byte[] inputBuffer = new byte[8];
234                         int i;
235                         ByteContainer inputBytes = new ByteContainer(400);
236                         do {
237                                 i = keyStream.read(inputBuffer);
238                                 for (int j = 0; j < i; j++) {
239                                         inputBytes.append(inputBuffer[j]);
240                                 }
241                         } while (i > -1);
242
243                         KeySpec keySpec = null;
244                         if (algorithm.equals("DESede")) keySpec = new DESedeKeySpec(inputBytes.toByteArray());
245                         else if (algorithm.equals("DES")) keySpec = new DESKeySpec(inputBytes.toByteArray());
246                         return keyFactory.generateSecret(keySpec);
247
248                 } catch (Exception e) {
249                         log.error("Problem reading secret key: " + e.getMessage());
250                         throw new ExtKeyToolException("Problem reading secret key.  Keys should be DER encoded native format.");
251                 }
252         }
253
254         /**
255          * Boolean indication of whether a given private key and public key form a valid keypair.
256          * 
257          * @param pubKey
258          *            the public key
259          * @param privKey
260          *            the private key
261          */
262
263         protected boolean isMatchingKey(String algorithm, PublicKey pubKey, PrivateKey privKey) {
264
265                 try {
266                         String controlString = "asdf";
267                         log.debug("Checking for matching private key/public key pair");
268
269                         /*
270                          * If both keys are RSA, compare the modulus. They can't be a pair if that doesn't match. Doing this early
271                          * check means we don't have to do a trial encryption for every public key (faster) and avoids warning
272                          * messages from the depths of the crypto provider if the key lengths differ.
273                          */
274                         if (privKey instanceof RSAKey && pubKey instanceof RSAKey) {
275                                 RSAKey pubRSA = (RSAKey) pubKey;
276                                 RSAKey privRSA = (RSAKey) privKey;
277                                 if (!privRSA.getModulus().equals(pubRSA.getModulus())) {
278                                         log.debug("RSA modulus mismatch");
279                                         return false;
280                                 }
281                         }
282
283                         Cipher cipher = Cipher.getInstance(algorithm);
284                         cipher.init(Cipher.ENCRYPT_MODE, pubKey);
285                         byte[] encryptedData = cipher.doFinal(controlString.getBytes("UTF-8"));
286
287                         cipher.init(Cipher.DECRYPT_MODE, privKey);
288                         byte[] decryptedData = cipher.doFinal(encryptedData);
289                         if (controlString.equals(new String(decryptedData, "UTF-8"))) {
290                                 log.debug("Found match.");
291                                 return true;
292                         }
293                 } catch (Exception e) {
294                         log.warn(e);
295                 }
296                 log.debug("This pair does not match.");
297                 return false;
298         }
299
300         /**
301          * Attempts to unmarshall a private key from a given stream.
302          * 
303          * @param keyStream
304          *            the <code>InputStream</code> suppying the key
305          * @param algorithm
306          *            the key algorithm
307          * @throws ExtKeyToolException
308          *             if there a problem unmarshalling the key
309          */
310
311         protected PrivateKey readPrivateKey(String provider, InputStream keyStream, String algorithm)
312                         throws ExtKeyToolException {
313
314                 try {
315                         KeyFactory keyFactory = KeyFactory.getInstance(algorithm, provider);
316
317                         byte[] inputBuffer = new byte[8];
318                         int i;
319                         ByteContainer inputBytes = new ByteContainer(400);
320                         do {
321                                 i = keyStream.read(inputBuffer);
322                                 for (int j = 0; j < i; j++) {
323                                         inputBytes.append(inputBuffer[j]);
324                                 }
325                         } while (i > -1);
326
327                         PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(inputBytes.toByteArray());
328                         return keyFactory.generatePrivate(keySpec);
329
330                 } catch (Exception e) {
331                         log.error("Problem reading private key: " + e.getMessage());
332                         throw new ExtKeyToolException(
333                                         "Problem reading private key.  Keys should be DER encoded pkcs8 or DER encoded native format.");
334                 }
335         }
336
337         /**
338          * Converts an array of certificates into an ordered chain. A certificate that matches the specified private key
339          * will be returned first and the root certificate will be returned last.
340          * 
341          * @param untestedCerts
342          *            array of certificates
343          * @param privKey
344          *            the private key used to determine the first cert in the chain
345          * @throws InvalidCertificateChainException
346          *             thrown if a chain cannot be constructed from the specified elements
347          */
348
349         protected X509Certificate[] linkChain(String keyAlgorithm, X509Certificate[] untestedCerts, PrivateKey privKey)
350                         throws InvalidCertificateChainException {
351
352                 log.debug("Located " + untestedCerts.length + " cert(s) in input file");
353
354                 log.info("Finding end cert in chain.");
355                 ArrayList replyCerts = new ArrayList();
356                 for (int i = 0; untestedCerts.length > i; i++) {
357                         if (isMatchingKey(keyAlgorithm, untestedCerts[i].getPublicKey(), privKey)) {
358                                 log.debug("Found matching end cert: " + untestedCerts[i].getSubjectDN());
359                                 replyCerts.add(untestedCerts[i]);
360                         }
361                 }
362                 if (replyCerts.size() < 1) {
363                         log.error("No certificate in chain that matches specified private key");
364                         throw new InvalidCertificateChainException("No certificate in chain that matches specified private key");
365                 }
366                 if (replyCerts.size() > 1) {
367                         log.error("More than one certificate in chain that matches specified private key");
368                         throw new InvalidCertificateChainException(
369                                         "More than one certificate in chain that matches specified private key");
370                 }
371
372                 log.info("Populating chain with remaining certs.");
373                 walkChain(untestedCerts, replyCerts);
374
375                 log.info("Verifying that each link in the cert chain is signed appropriately");
376                 for (int i = 0; i < replyCerts.size() - 1; i++) {
377                         PublicKey pubKey = ((X509Certificate) replyCerts.get(i + 1)).getPublicKey();
378                         try {
379                                 ((X509Certificate) replyCerts.get(i)).verify(pubKey);
380                         } catch (Exception e) {
381                                 log.error("Certificate chain cannot be verified: " + e.getMessage());
382                                 throw new InvalidCertificateChainException("Certificate chain cannot be verified: " + e.getMessage());
383                         }
384                 }
385                 log.info("All signatures verified. Certificate chain successfully created.");
386
387                 return (X509Certificate[]) replyCerts.toArray(new X509Certificate[0]);
388         }
389
390         /**
391          * Given an ArrayList containing a base certificate and an array of unordered certificates, populates the ArrayList
392          * with an ordered certificate chain, based on subject and issuer.
393          * 
394          * @param chainSource
395          *            array of certificates to pull from
396          * @param chainDest
397          *            ArrayList containing base certificate
398          * @throws InvalidCertificateChainException
399          *             thrown if a chain cannot be constructed from the specified elements
400          */
401
402         protected void walkChain(X509Certificate[] chainSource, ArrayList chainDest)
403                         throws InvalidCertificateChainException {
404
405                 X509Certificate currentCert = (X509Certificate) chainDest.get(chainDest.size() - 1);
406                 if (currentCert.getSubjectDN().equals(currentCert.getIssuerDN())) {
407                         log.debug("Found self-signed root cert: " + currentCert.getSubjectDN());
408                         return;
409                 } else {
410                         for (int i = 0; chainSource.length > i; i++) {
411                                 if (currentCert.getIssuerDN().equals(chainSource[i].getSubjectDN())) {
412                                         chainDest.add(chainSource[i]);
413                                         walkChain(chainSource, chainDest);
414                                         return;
415                                 }
416                         }
417                         log.error("Incomplete certificate chain.");
418                         throw new InvalidCertificateChainException("Incomplete cerficate chain.");
419                 }
420         }
421
422         /**
423          * Given a java keystore, private key, and matching certificate chain; creates a new keystore containing the union
424          * of these objects
425          * 
426          * @param provider
427          *            the name of the jce provider to use
428          * @param keyAlgorithm
429          *            the algorithm of the key to be added, defaults to RSA if null
430          * @param keyStream
431          *            strema used to retrieve the private key, can contain a PEM encoded or pkcs8 encoded key
432          * @param chainStream
433          *            stream used to retrieve certificates, can contain a series of PEM encoded certs or a pkcs7 chain
434          * @param keyStoreInStream
435          *            stream used to retrieve the initial keystore
436          * @param storeType
437          *            the type of the keystore
438          * @param keyAlias
439          *            the alias under which the key/chain should be saved
440          * @param keyStorePassword
441          *            password used to verify the integrity of the old keystore and save the new keystore
442          * @param keyPassword
443          *            the password for saving the key
444          * @param secret
445          *            indicates this is a secret key import
446          * @return an OutputStream containing the new keystore
447          * @throws ExtKeyToolException
448          *             if there a problem importing the key
449          */
450
451         public ByteArrayOutputStream importKey(String provider, String keyAlgorithm, InputStream keyStream,
452                         InputStream chainStream, InputStream keyStoreInStream, String storeType, String keyAlias,
453                         char[] keyStorePassword, char[] keyPassword, boolean secret) throws ExtKeyToolException {
454
455                 log.info("Importing " + (secret ? "key pair" : "secret key."));
456                 try {
457
458                         // The Sun provider incorrectly reads only the first cert in the stream.
459                         // No loss, it won't even read RSA keys
460                         if (provider == "SUN") {
461                                 log.error("Sorry, this function not supported with the SUN provider.");
462                                 throw new ExtKeyToolException("Sorry, this function not supported with the SUN provider.");
463                         }
464
465                         KeyStore keyStore = loadKeyStore(provider, keyStoreInStream, storeType, keyStorePassword);
466
467                         if (keyAlias == null) {
468                                 log.error("Key alias must be specified.");
469                                 throw new ExtKeyToolException("Key alias must be specified.");
470                         }
471                         if (keyStore.containsAlias(keyAlias) == true && keyStore.isKeyEntry(keyAlias)) {
472                                 log.error("Could not import key: " + "key alias (" + keyAlias + ") already exists");
473                                 throw new ExtKeyToolException("Could not import key: " + "key alias (" + keyAlias + ") already exists");
474                         }
475                         keyStore.deleteEntry(keyAlias);
476
477                         if (secret) {
478                                 log.info("Reading secret key.");
479                                 if (keyAlgorithm == null) {
480                                         keyAlgorithm = "AES";
481                                 }
482                                 log.debug("Using key algorithm: (" + keyAlgorithm + ")");
483                                 SecretKey key = readSecretKey(provider, keyStream, keyAlgorithm);
484                                 keyStore.setKeyEntry(keyAlias, key, keyPassword, null);
485                         } else {
486                                 log.info("Reading private key.");
487                                 if (keyAlgorithm == null) {
488                                         keyAlgorithm = "RSA";
489                                 }
490                                 log.debug("Using key algorithm: (" + keyAlgorithm + ")");
491                                 PrivateKey key = readPrivateKey(provider, keyStream, keyAlgorithm);
492
493                                 log.info("Reading certificate chain.");
494
495                                 CertificateFactory certFactory = CertificateFactory.getInstance("X.509", provider);
496                                 Collection chain = certFactory.generateCertificates(new BufferedInputStream(chainStream));
497                                 if (chain.isEmpty()) {
498                                         log.error("Input did not contain any valid certificates.");
499                                         throw new ExtKeyToolException("Input did not contain any valid certificates.");
500                                 }
501
502                                 X509Certificate[] verifiedChain = linkChain(keyAlgorithm, (X509Certificate[]) chain
503                                                 .toArray(new X509Certificate[0]), key);
504
505                                 keyStore.setKeyEntry(keyAlias, key, keyPassword, verifiedChain);
506                         }
507
508                         ByteArrayOutputStream keyStoreOutStream = new ByteArrayOutputStream();
509                         keyStore.store(keyStoreOutStream, keyStorePassword);
510                         log.info("Key Store saved to stream.");
511                         return keyStoreOutStream;
512
513                 } catch (KeyStoreException e) {
514                         log.error("Encountered a problem accessing the keystore: " + e.getMessage());
515                         throw new ExtKeyToolException("Encountered a problem accessing the keystore: " + e.getMessage());
516                 } catch (CertificateException e) {
517                         log.error("Could not load certificate(s): " + e.getMessage());
518                         throw new ExtKeyToolException("Could not load certificate(s): " + e.getMessage());
519                 } catch (NoSuchProviderException e) {
520                         log.error("The specified provider is not available.");
521                         throw new ExtKeyToolException("The specified provider is not available.");
522                 } catch (IOException ioe) {
523                         log.error("Could not export key: " + ioe);
524                         throw new ExtKeyToolException("Could not export key: " + ioe);
525                 } catch (NoSuchAlgorithmException nse) {
526                         log.error("Could not save with the installed JCE providers: " + nse);
527                         throw new ExtKeyToolException("Could not save with the installed JCE providers: " + nse);
528                 }
529         }
530
531         /**
532          * Tries to decipher command line arguments.
533          * 
534          * @throws IllegalArgumentException
535          *             if arguments are not properly formatted
536          */
537
538         private static Properties parseArguments(String[] args) throws IllegalArgumentException {
539
540                 if (args.length < 1) { throw new IllegalArgumentException("No arguments found."); }
541                 Properties parsedArguments = new Properties();
542
543                 for (int i = 0; (i < args.length) && args[i].startsWith("-"); i++) {
544
545                         String flags = args[i];
546
547                         // parse actions
548                         if (flags.equalsIgnoreCase("-exportkey")) {
549                                 parsedArguments.setProperty("command", "exportKey");
550                         } else if (flags.equalsIgnoreCase("-importkey")) {
551                                 parsedArguments.setProperty("command", "importKey");
552                         }
553
554                         // parse specifiers
555                         else if (flags.equalsIgnoreCase("-secret")) {
556                                 parsedArguments.setProperty("secret", "true");
557                         } else if (flags.equalsIgnoreCase("-alias")) {
558                                 if (++i == args.length) { throw new IllegalArgumentException("The argument -alias requires a parameter"); }
559                                 parsedArguments.setProperty("alias", args[i]);
560                         } else if (flags.equalsIgnoreCase("-keyfile")) {
561                                 if (++i == args.length) { throw new IllegalArgumentException(
562                                                 "The argument -keyfile requires a parameter"); }
563                                 parsedArguments.setProperty("keyFile", args[i]);
564                         } else if (flags.equalsIgnoreCase("-certfile")) {
565                                 if (++i == args.length) { throw new IllegalArgumentException(
566                                                 "The argument -certfile requires a parameter"); }
567                                 parsedArguments.setProperty("certFile", args[i]);
568                         } else if (flags.equalsIgnoreCase("-keystore")) {
569                                 if (++i == args.length) { throw new IllegalArgumentException(
570                                                 "The argument -keystore requires a parameter"); }
571                                 parsedArguments.setProperty("keyStore", args[i]);
572                         } else if (flags.equalsIgnoreCase("-storepass")) {
573                                 if (++i == args.length) { throw new IllegalArgumentException(
574                                                 "The argument -storepass requires a parameter"); }
575                                 parsedArguments.setProperty("storePass", args[i]);
576                         } else if (flags.equalsIgnoreCase("-storetype")) {
577                                 if (++i == args.length) { throw new IllegalArgumentException(
578                                                 "The argument -storetype requires a parameter"); }
579                                 parsedArguments.setProperty("storeType", args[i]);
580                         } else if (flags.equalsIgnoreCase("-keypass")) {
581                                 if (++i == args.length) { throw new IllegalArgumentException(
582                                                 "The argument -keypass requires a parameter"); }
583                                 parsedArguments.setProperty("keyPass", args[i]);
584                         } else if (flags.equalsIgnoreCase("-provider")) {
585                                 if (++i == args.length) { throw new IllegalArgumentException(
586                                                 "The argument -provider requires a parameter"); }
587                                 parsedArguments.setProperty("provider", args[i]);
588                         } else if (flags.equalsIgnoreCase("-file")) {
589                                 if (++i == args.length) { throw new IllegalArgumentException("The argument -file requires a parameter"); }
590                                 parsedArguments.setProperty("file", args[i]);
591                         } else if (flags.equalsIgnoreCase("-algorithm")) {
592                                 if (++i == args.length) { throw new IllegalArgumentException(
593                                                 "The argument -algorithm requires a parameter"); }
594                                 parsedArguments.setProperty("keyAlgorithm", args[i]);
595                         }
596
597                         // options
598                         else if (flags.equalsIgnoreCase("-v")) {
599                                 parsedArguments.setProperty("verbose", "true");
600                         } else if (flags.equalsIgnoreCase("-rfc")) {
601                                 parsedArguments.setProperty("rfc", "true");
602                         } else {
603                                 throw new IllegalArgumentException("Unrecognized argument: " + flags);
604                         }
605                 }
606                 if (parsedArguments.getProperty("command", null) == null) { throw new IllegalArgumentException(
607                                 "No action specified"); }
608                 return parsedArguments;
609         }
610
611         /**
612          * Ensures that providers specified on the command line are in fact loaded into the current environment.
613          * 
614          * @return the name of the provider add, null if no provider was added
615          */
616
617         protected String initProvider(Properties arguments) {
618
619                 try {
620                         if (arguments.getProperty("provider", null) != null) {
621
622                                 Provider provider = (Provider) Class.forName(arguments.getProperty("provider")).newInstance();
623                                 log.info("Adding Provider to environment: (" + provider.getName() + ")");
624                                 Security.addProvider(provider);
625                                 return provider.getName();
626                         }
627                 } catch (Exception e) {
628                         log.error("Could not load specified jce provider: " + e);
629                 }
630                 return null;
631
632         }
633
634         /**
635          * Initializes Log4J logger mode based on command line arguments.
636          */
637
638         protected void startLogger(Properties arguments) {
639
640                 Logger root = Logger.getRootLogger();
641                 if (arguments.getProperty("verbose", null) == null || arguments.getProperty("verbose", null).equals("false")) {
642                         root.addAppender(new ConsoleAppender(new PatternLayout(PatternLayout.DEFAULT_CONVERSION_PATTERN)));
643                         root.setLevel(Level.WARN);
644                 } else {
645                         root.addAppender(new ConsoleAppender(new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN)));
646                         root.setLevel(Level.DEBUG);
647                 }
648         }
649
650         public static void main(String[] args) {
651
652                 try {
653                         ExtKeyTool tool = new ExtKeyTool();
654                         Properties arguments = null;
655                         try {
656                                 arguments = parseArguments(args);
657                         } catch (IllegalArgumentException iae) {
658                                 System.err.println("Illegal argument specified: " + iae.getMessage()
659                                                 + System.getProperty("line.separator"));
660                                 printUsage(System.err);
661                                 System.exit(1);
662                         }
663                         tool.startLogger(arguments);
664                         String providerName = tool.initProvider(arguments);
665                         if (providerName != null) {
666                                 arguments.setProperty("providerName", providerName);
667                         }
668                         tool.run(arguments);
669
670                 } catch (ExtKeyToolException ske) {
671                         log.fatal("Cannot Perform Operation: " + ske.getMessage() + System.getProperty("line.separator"));
672                         LogManager.shutdown();
673                         printUsage(System.err);
674                 }
675         }
676
677         /**
678          * Based on on a set of properties, executes <code>ExtKeyTool</code> actions.
679          * 
680          * @param arguments
681          *            runtime parameters specified on the command line
682          */
683
684         private void run(Properties arguments) throws ExtKeyToolException {
685
686                 // common for all actions
687                 char[] storePassword = null;
688                 if (arguments.getProperty("storePass", null) != null) {
689                         storePassword = arguments.getProperty("storePass").toCharArray();
690                 }
691
692                 String providerName = null;
693                 if (arguments.getProperty("providerName", null) != null) {
694                         providerName = arguments.getProperty("providerName");
695                 } else {
696                         providerName = "SUN";
697                 }
698
699                 // export key action
700                 if (arguments.getProperty("command").equals("exportKey")) {
701
702                         boolean rfc = false;
703                         if ("true".equalsIgnoreCase(arguments.getProperty("rfc", null))) {
704                                 rfc = true;
705                         }
706
707                         PrintStream outStream = null;
708                         if (arguments.getProperty("file", null) != null) {
709                                 try {
710                                         outStream = new PrintStream(new FileOutputStream(arguments.getProperty("file")));
711                                 } catch (FileNotFoundException e) {
712                                         throw new ExtKeyToolException("Could not open output file: " + e);
713                                 }
714                         } else {
715                                 outStream = System.out;
716                         }
717
718                         try {
719                                 exportKey(providerName, outStream, new FileInputStream(resolveKeyStore(arguments.getProperty(
720                                                 "keyStore", null))), arguments.getProperty("storeType", null), storePassword, arguments
721                                                 .getProperty("alias", null), resolveKeyPass(arguments.getProperty("keyPass", null),
722                                                 storePassword), rfc);
723                         } catch (FileNotFoundException e) {
724                                 throw new ExtKeyToolException("KeyStore not found.");
725                         }
726                         outStream.close();
727
728                         // import action
729                 } else if (arguments.getProperty("command").equals("importKey")) {
730
731                         InputStream keyInStream = null;
732                         if (arguments.getProperty("keyFile", null) != null) {
733                                 try {
734                                         keyInStream = new FileInputStream(arguments.getProperty("keyFile"));
735                                 } catch (FileNotFoundException e) {
736                                         throw new ExtKeyToolException("Could not open key file." + e.getMessage());
737                                 }
738                         } else {
739                                 throw new IllegalArgumentException("Key file must be specified.");
740                         }
741
742                         InputStream certInStream = null;
743                         if (arguments.getProperty("certFile", null) != null) {
744                                 try {
745                                         certInStream = new FileInputStream(arguments.getProperty("certFile"));
746                                 } catch (FileNotFoundException e) {
747                                         throw new ExtKeyToolException("Could not open cert file." + e.getMessage());
748                                 }
749                         } else if (!arguments.getProperty("secret").equalsIgnoreCase("true")) { throw new IllegalArgumentException(
750                                         "Certificate file must be specified."); }
751
752                         try {
753
754                                 ByteArrayOutputStream keyStoreOutStream = importKey(providerName, arguments.getProperty("keyAlgorithm",
755                                                 null), keyInStream, certInStream, new FileInputStream(resolveKeyStore(arguments.getProperty(
756                                                 "keyStore", null))), arguments.getProperty("storeType", null), arguments.getProperty("alias",
757                                                 null), storePassword, resolveKeyPass(arguments.getProperty("keyPass", null), storePassword),
758                                                 arguments.getProperty("secret", "false").equalsIgnoreCase("true"));
759
760                                 keyInStream.close();
761                                 // A quick sanity check before we overwrite the old keystore
762                                 if (keyStoreOutStream == null || keyStoreOutStream.size() < 1) { throw new ExtKeyToolException(
763                                                 "Failed to create keystore: results are null"); }
764                                 keyStoreOutStream
765                                                 .writeTo(new FileOutputStream(resolveKeyStore(arguments.getProperty("keyStore", null))));
766                                 System.out.println("Key import successful.");
767
768                         } catch (FileNotFoundException e) {
769                                 throw new ExtKeyToolException("Could not open keystore file." + e.getMessage());
770                         } catch (IOException e) {
771                                 throw new ExtKeyToolException("Error writing keystore." + e.getMessage());
772                         }
773
774                 } else {
775                         throw new IllegalArgumentException("This keytool cannot perform the operation: ("
776                                         + arguments.getProperty("command") + ")");
777                 }
778
779         }
780
781         /**
782          * Determines the location of the keystore to use when performing the action
783          * 
784          * @return the <code>File</code> representation of the selected keystore
785          */
786
787         protected File resolveKeyStore(String keyStoreLocation) throws ExtKeyToolException, FileNotFoundException {
788
789                 if (keyStoreLocation == null) {
790                         keyStoreLocation = System.getProperty("user.home") + File.separator + ".keystore";
791                 }
792                 log.debug("Using keystore (" + keyStoreLocation + ")");
793                 File file = new File(keyStoreLocation);
794                 if (file.exists() && file.length() == 0) {
795                         log.error("Keystore file is empty.");
796                         throw new ExtKeyToolException("Keystore file is empty.");
797                 }
798                 return file;
799         }
800
801         /**
802          * Decides what password to use for storing/retrieving keys from the keystore. NOTE: Possible terminal interaction
803          * with the user.
804          * 
805          * @return a char array containing the password
806          */
807
808         protected char[] resolveKeyPass(String keyPass, char[] storePass) {
809
810                 if (keyPass != null) {
811                         return keyPass.toCharArray();
812                 } else {
813                         System.out.println("Enter key password");
814                         System.out.print("\t(RETURN if same as keystore password):  ");
815                         System.out.flush();
816                         try {
817                                 BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
818                                 String passwordInput = reader.readLine();
819                                 passwordInput.trim();
820                                 if (passwordInput != null && !passwordInput.equals("")) { return passwordInput.toCharArray(); }
821                         } catch (IOException e) {
822                                 log.warn(e.getMessage());
823                         }
824                         log.warn("No password specified, defaulting to keystore password.");
825                         return storePass;
826                 }
827         }
828
829         private static void printUsage(PrintStream out) {
830
831                 out.println("extkeytool usage:");
832                 out.print("-exportkey      [-v] [-rfc] [-alias <alias>] ");
833                 out.println("[-keystore <keystore>] ");
834                 out.print("\t     [-storepass <storepass>] ");
835                 out.println("[-storetype <storetype>]");
836                 out.print("\t     [-keypass <keypass>] ");
837                 out.println("[-provider <provider_class_name>] ");
838                 out.print("\t     [-file <output_file>] ");
839                 out.println();
840                 out.println();
841
842                 out.print("-importkey      [-v] [-secret] [-alias <alias>] ");
843                 out.println("[-keyfile <key_file>]");
844                 out.print("\t     [-keystore <keystore>] ");
845                 out.println("[-storepass <storepass>]");
846                 out.print("\t     [-storetype <storetype>] ");
847                 out.println("[-keypass <keypass>] ");
848                 out.print("\t     [-provider <provider_class_name>] ");
849                 out.println("[-certfile <cert_file>] ");
850                 out.print("\t     [-algorithm <key_algorithm>] ");
851                 out.println();
852
853         }
854
855         /**
856          * Auto-enlarging container for bytes.
857          */
858
859         // Sure makes you wish bytes were first class objects.
860         private class ByteContainer {
861
862                 private byte[] buffer;
863                 private int cushion;
864                 private int currentSize = 0;
865
866                 private ByteContainer(int cushion) {
867
868                         buffer = new byte[cushion];
869                         this.cushion = cushion;
870                 }
871
872                 private void grow() {
873
874                         log.debug("Growing ByteContainer.");
875                         int newSize = currentSize + cushion;
876                         byte[] b = new byte[newSize];
877                         int toCopy = Math.min(currentSize, newSize);
878                         int i;
879                         for (i = 0; i < toCopy; i++) {
880                                 b[i] = buffer[i];
881                         }
882                         buffer = b;
883                 }
884
885                 /**
886                  * Returns an array of the bytes in the container.
887                  * <p>
888                  */
889
890                 private byte[] toByteArray() {
891
892                         byte[] b = new byte[currentSize];
893                         for (int i = 0; i < currentSize; i++) {
894                                 b[i] = buffer[i];
895                         }
896                         return b;
897                 }
898
899                 /**
900                  * Add one byte to the end of the container.
901                  */
902
903                 private void append(byte b) {
904
905                         if (currentSize == buffer.length) {
906                                 grow();
907                         }
908                         buffer[currentSize] = b;
909                         currentSize++;
910                 }
911
912         }
913
914         /**
915          * Signals that an error was encounted while using <code>ExtKeyTool</code> functions.
916          */
917
918         protected class ExtKeyToolException extends Exception {
919
920                 protected ExtKeyToolException(String message) {
921
922                         super(message);
923                 }
924         }
925
926         /**
927          * Signals that an error occurred while trying to constuct a certificate chain.
928          */
929
930         protected class InvalidCertificateChainException extends ExtKeyToolException {
931
932                 protected InvalidCertificateChainException(String message) {
933
934                         super(message);
935                 }
936         }
937
938 }