Fix up library versions and classpath
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / utils / ExtKeyTool.java
index 0bef448..2dade76 100755 (executable)
@@ -1,26 +1,17 @@
 /*
- * The Shibboleth License, Version 1. Copyright (c) 2002 University Corporation for Advanced Internet Development, Inc.
- * All rights reserved Redistribution and use in source and binary forms, with or without modification, are permitted
- * provided that the following conditions are met: Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials
- * provided with the distribution, if any, must include the following acknowledgment: "This product includes software
- * developed by the University Corporation for Advanced Internet Development <http://www.ucaid.edu>Internet2 Project.
- * Alternately, this acknowledegement may appear in the software itself, if and wherever such third-party
- * acknowledgments normally appear. Neither the name of Shibboleth nor the names of its contributors, nor Internet2, nor
- * the University Corporation for Advanced Internet Development, Inc., nor UCAID may be used to endorse or promote
- * products derived from this software without specific prior written permission. For written permission, please contact
- * shibboleth@shibboleth.org Products derived from this software may not be called Shibboleth, Internet2, UCAID, or the
- * University Corporation for Advanced Internet Development, nor may Shibboleth appear in their name, without prior
- * written permission of the University Corporation for Advanced Internet Development. THIS SOFTWARE IS PROVIDED BY THE
- * COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND WITH ALL FAULTS. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE
- * DISCLAIMED AND THE ENTIRE RISK OF SATISFACTORY QUALITY, PERFORMANCE, ACCURACY, AND EFFORT IS WITH LICENSEE. IN NO
- * EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY CORPORATION FOR ADVANCED INTERNET DEVELOPMENT, INC.
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
- * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * Copyright [2005] [University Corporation for Advanced Internet Development, Inc.]
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
  */
 
 package edu.internet2.middleware.shibboleth.utils;
@@ -35,6 +26,7 @@ import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.InputStreamReader;
+import java.io.OutputStream;
 import java.io.PrintStream;
 import java.security.Key;
 import java.security.KeyFactory;
@@ -47,27 +39,33 @@ import java.security.Provider;
 import java.security.PublicKey;
 import java.security.Security;
 import java.security.UnrecoverableKeyException;
+import java.security.cert.Certificate;
 import java.security.cert.CertificateException;
 import java.security.cert.CertificateFactory;
 import java.security.cert.X509Certificate;
 import java.security.interfaces.RSAKey;
+import java.security.spec.KeySpec;
 import java.security.spec.PKCS8EncodedKeySpec;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Properties;
 
 import javax.crypto.Cipher;
+import javax.crypto.SecretKey;
+import javax.crypto.SecretKeyFactory;
+import javax.crypto.spec.DESKeySpec;
+import javax.crypto.spec.DESedeKeySpec;
 
 import org.apache.log4j.ConsoleAppender;
 import org.apache.log4j.Level;
 import org.apache.log4j.LogManager;
 import org.apache.log4j.Logger;
 import org.apache.log4j.PatternLayout;
-import sun.misc.BASE64Encoder;
+import org.bouncycastle.util.encoders.Base64;
 
 /**
  * Extension utility for use alongside Sun's keytool program. Performs useful functions not found in original.
- * 
+ *
  * @author Walter Hoehn
  */
 
@@ -139,6 +137,20 @@ public class ExtKeyTool {
                }
        }
 
+       private void writeWithWrapping(byte[] base64text, int linesize, OutputStream out)
+       throws IOException
+       {
+               int length = base64text.length;
+               if (length == 0) return;
+
+               out.write( (int)base64text[0] );
+               for (int i=1; i < length; i++)
+               {
+                       if (i%linesize == 0) out.write('\n');
+                       out.write( (int)base64text[i] );
+               }
+       }
+
        /**
         * Retrieves a private key from a java keystore and writes it to an <code>PrintStream</code>
         * 
@@ -182,15 +194,17 @@ public class ExtKeyTool {
                        }
                        log.info("Found key.");
 
+                       byte[] encodedKey = key.getEncoded();
+
                        if (rfc) {
                                log.debug("Dumping with rfc encoding");
                                outStream.println("-----BEGIN PRIVATE KEY-----");
-                               BASE64Encoder encoder = new BASE64Encoder();
-                               encoder.encodeBuffer(key.getEncoded(), outStream);
+                               writeWithWrapping(Base64.encode(encodedKey), 76, outStream);
+                               outStream.println();
                                outStream.println("-----END PRIVATE KEY-----");
                        } else {
                                log.debug("Dumping with default encoding.");
-                               outStream.write(key.getEncoded());
+                               outStream.write(encodedKey);
                        }
 
                } catch (KeyStoreException e) {
@@ -209,6 +223,44 @@ public class ExtKeyTool {
        }
 
        /**
+        * Attempts to unmarshall a secret key from a given stream.
+        * 
+        * @param keyStream
+        *            the <code>InputStream</code> suppying the key
+        * @param algorithm
+        *            the key algorithm
+        * @throws ExtKeyToolException
+        *             if there a problem unmarshalling the key
+        */
+
+       protected SecretKey readSecretKey(String provider, InputStream keyStream, String algorithm)
+                       throws ExtKeyToolException {
+
+               try {
+                       SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm, provider);
+
+                       byte[] inputBuffer = new byte[8];
+                       int i;
+                       ByteContainer inputBytes = new ByteContainer(400);
+                       do {
+                               i = keyStream.read(inputBuffer);
+                               for (int j = 0; j < i; j++) {
+                                       inputBytes.append(inputBuffer[j]);
+                               }
+                       } while (i > -1);
+
+                       KeySpec keySpec = null;
+                       if (algorithm.equals("DESede")) keySpec = new DESedeKeySpec(inputBytes.toByteArray());
+                       else if (algorithm.equals("DES")) keySpec = new DESKeySpec(inputBytes.toByteArray());
+                       return keyFactory.generateSecret(keySpec);
+
+               } catch (Exception e) {
+                       log.error("Problem reading secret key: " + e.getMessage());
+                       throw new ExtKeyToolException("Problem reading secret key.  Keys should be DER encoded native format.");
+               }
+       }
+
+       /**
         * Boolean indication of whether a given private key and public key form a valid keypair.
         * 
         * @param pubKey
@@ -309,7 +361,7 @@ public class ExtKeyTool {
                log.debug("Located " + untestedCerts.length + " cert(s) in input file");
 
                log.info("Finding end cert in chain.");
-               ArrayList replyCerts = new ArrayList();
+               ArrayList<X509Certificate> replyCerts = new ArrayList<X509Certificate>();
                for (int i = 0; untestedCerts.length > i; i++) {
                        if (isMatchingKey(keyAlgorithm, untestedCerts[i].getPublicKey(), privKey)) {
                                log.debug("Found matching end cert: " + untestedCerts[i].getSubjectDN());
@@ -356,7 +408,7 @@ public class ExtKeyTool {
         *             thrown if a chain cannot be constructed from the specified elements
         */
 
-       protected void walkChain(X509Certificate[] chainSource, ArrayList chainDest)
+       protected void walkChain(X509Certificate[] chainSource, ArrayList<X509Certificate> chainDest)
                        throws InvalidCertificateChainException {
 
                X509Certificate currentCert = (X509Certificate) chainDest.get(chainDest.size() - 1);
@@ -398,6 +450,8 @@ public class ExtKeyTool {
         *            password used to verify the integrity of the old keystore and save the new keystore
         * @param keyPassword
         *            the password for saving the key
+        * @param secret
+        *            indicates this is a secret key import
         * @return an OutputStream containing the new keystore
         * @throws ExtKeyToolException
         *             if there a problem importing the key
@@ -405,9 +459,9 @@ public class ExtKeyTool {
 
        public ByteArrayOutputStream importKey(String provider, String keyAlgorithm, InputStream keyStream,
                        InputStream chainStream, InputStream keyStoreInStream, String storeType, String keyAlias,
-                       char[] keyStorePassword, char[] keyPassword) throws ExtKeyToolException {
+                       char[] keyStorePassword, char[] keyPassword, boolean secret) throws ExtKeyToolException {
 
-               log.info("Importing key pair.");
+               log.info("Importing " + (secret ? "key pair" : "secret key."));
                try {
 
                        // The Sun provider incorrectly reads only the first cert in the stream.
@@ -429,26 +483,38 @@ public class ExtKeyTool {
                        }
                        keyStore.deleteEntry(keyAlias);
 
-                       log.info("Reading private key.");
-                       if (keyAlgorithm == null) {
-                               keyAlgorithm = "RSA";
-                       }
-                       log.debug("Using key algorithm: (" + keyAlgorithm + ")");
-                       PrivateKey key = readPrivateKey(provider, keyStream, keyAlgorithm);
+                       if (secret) {
+                               log.info("Reading secret key.");
+                               if (keyAlgorithm == null) {
+                                       keyAlgorithm = "AES";
+                               }
+                               log.debug("Using key algorithm: (" + keyAlgorithm + ")");
+                               SecretKey key = readSecretKey(provider, keyStream, keyAlgorithm);
+                               keyStore.setKeyEntry(keyAlias, key, keyPassword, null);
+                       } else {
+                               log.info("Reading private key.");
+                               if (keyAlgorithm == null) {
+                                       keyAlgorithm = "RSA";
+                               }
+                               log.debug("Using key algorithm: (" + keyAlgorithm + ")");
+                               PrivateKey key = readPrivateKey(provider, keyStream, keyAlgorithm);
 
-                       log.info("Reading certificate chain.");
+                               log.info("Reading certificate chain.");
 
-                       CertificateFactory certFactory = CertificateFactory.getInstance("X.509", provider);
-                       Collection chain = certFactory.generateCertificates(new BufferedInputStream(chainStream));
-                       if (chain.isEmpty()) {
-                               log.error("Input did not contain any valid certificates.");
-                               throw new ExtKeyToolException("Input did not contain any valid certificates.");
-                       }
+                               CertificateFactory certFactory = CertificateFactory.getInstance("X.509", provider);
+                               Collection<? extends Certificate> chain = certFactory.generateCertificates(new BufferedInputStream(
+                                               chainStream));
+                               if (chain.isEmpty()) {
+                                       log.error("Input did not contain any valid certificates.");
+                                       throw new ExtKeyToolException("Input did not contain any valid certificates.");
+                               }
+
+                               X509Certificate[] verifiedChain = linkChain(keyAlgorithm, (X509Certificate[]) chain
+                                               .toArray(new X509Certificate[0]), key);
 
-                       X509Certificate[] verifiedChain = linkChain(keyAlgorithm, (X509Certificate[]) chain
-                                       .toArray(new X509Certificate[0]), key);
+                               keyStore.setKeyEntry(keyAlias, key, keyPassword, verifiedChain);
+                       }
 
-                       keyStore.setKeyEntry(keyAlias, key, keyPassword, verifiedChain);
                        ByteArrayOutputStream keyStoreOutStream = new ByteArrayOutputStream();
                        keyStore.store(keyStoreOutStream, keyStorePassword);
                        log.info("Key Store saved to stream.");
@@ -488,15 +554,17 @@ public class ExtKeyTool {
 
                        String flags = args[i];
 
-                       //parse actions
+                       // parse actions
                        if (flags.equalsIgnoreCase("-exportkey")) {
                                parsedArguments.setProperty("command", "exportKey");
                        } else if (flags.equalsIgnoreCase("-importkey")) {
                                parsedArguments.setProperty("command", "importKey");
                        }
 
-                       //parse specifiers
-                       else if (flags.equalsIgnoreCase("-alias")) {
+                       // parse specifiers
+                       else if (flags.equalsIgnoreCase("-secret")) {
+                               parsedArguments.setProperty("secret", "true");
+                       } else if (flags.equalsIgnoreCase("-alias")) {
                                if (++i == args.length) { throw new IllegalArgumentException("The argument -alias requires a parameter"); }
                                parsedArguments.setProperty("alias", args[i]);
                        } else if (flags.equalsIgnoreCase("-keyfile")) {
@@ -536,7 +604,7 @@ public class ExtKeyTool {
                                parsedArguments.setProperty("keyAlgorithm", args[i]);
                        }
 
-                       //options
+                       // options
                        else if (flags.equalsIgnoreCase("-v")) {
                                parsedArguments.setProperty("verbose", "true");
                        } else if (flags.equalsIgnoreCase("-rfc")) {
@@ -625,7 +693,7 @@ public class ExtKeyTool {
 
        private void run(Properties arguments) throws ExtKeyToolException {
 
-               //common for all actions
+               // common for all actions
                char[] storePassword = null;
                if (arguments.getProperty("storePass", null) != null) {
                        storePassword = arguments.getProperty("storePass").toCharArray();
@@ -638,7 +706,7 @@ public class ExtKeyTool {
                        providerName = "SUN";
                }
 
-               //export key action
+               // export key action
                if (arguments.getProperty("command").equals("exportKey")) {
 
                        boolean rfc = false;
@@ -667,7 +735,7 @@ public class ExtKeyTool {
                        }
                        outStream.close();
 
-                       //import action
+                       // import action
                } else if (arguments.getProperty("command").equals("importKey")) {
 
                        InputStream keyInStream = null;
@@ -688,16 +756,16 @@ public class ExtKeyTool {
                                } catch (FileNotFoundException e) {
                                        throw new ExtKeyToolException("Could not open cert file." + e.getMessage());
                                }
-                       } else {
-                               throw new IllegalArgumentException("Certificate file must be specified.");
-                       }
+                       } else if (!arguments.getProperty("secret").equalsIgnoreCase("true")) { throw new IllegalArgumentException(
+                                       "Certificate file must be specified."); }
 
                        try {
 
                                ByteArrayOutputStream keyStoreOutStream = importKey(providerName, arguments.getProperty("keyAlgorithm",
                                                null), keyInStream, certInStream, new FileInputStream(resolveKeyStore(arguments.getProperty(
                                                "keyStore", null))), arguments.getProperty("storeType", null), arguments.getProperty("alias",
-                                               null), storePassword, resolveKeyPass(arguments.getProperty("keyPass", null), storePassword));
+                                               null), storePassword, resolveKeyPass(arguments.getProperty("keyPass", null), storePassword),
+                                               arguments.getProperty("secret", "false").equalsIgnoreCase("true"));
 
                                keyInStream.close();
                                // A quick sanity check before we overwrite the old keystore
@@ -781,7 +849,7 @@ public class ExtKeyTool {
                out.println();
                out.println();
 
-               out.print("-importkey      [-v] [-alias <alias>] ");
+               out.print("-importkey      [-v] [-secret] [-alias <alias>] ");
                out.println("[-keyfile <key_file>]");
                out.print("\t     [-keystore <keystore>] ");
                out.println("[-storepass <storepass>]");