You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@directory.apache.org by dr...@apache.org on 2015/12/13 03:02:08 UTC
[17/36] directory-kerby git commit: Moved the source codes of
not-so-commons-ssl into kerby-pkix module and cleaned up accordingly
http://git-wip-us.apache.org/repos/asf/directory-kerby/blob/a2c604ee/kerby-pkix/src/main/java/org/apache/commons/ssl/Java14.java
----------------------------------------------------------------------
diff --git a/kerby-pkix/src/main/java/org/apache/commons/ssl/Java14.java b/kerby-pkix/src/main/java/org/apache/commons/ssl/Java14.java
new file mode 100644
index 0000000..d8618ab
--- /dev/null
+++ b/kerby-pkix/src/main/java/org/apache/commons/ssl/Java14.java
@@ -0,0 +1,268 @@
+/*
+ * $HeadURL: http://juliusdavies.ca/svn/not-yet-commons-ssl/tags/commons-ssl-0.3.16/src/java/org/apache/commons/ssl/Java14.java $
+ * $Revision: 166 $
+ * $Date: 2014-04-28 11:40:25 -0700 (Mon, 28 Apr 2014) $
+ *
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+
+package org.apache.commons.ssl;
+
+import javax.net.SocketFactory;
+import javax.net.ssl.KeyManager;
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLPeerUnverifiedException;
+import javax.net.ssl.SSLServerSocket;
+import javax.net.ssl.SSLServerSocketFactory;
+import javax.net.ssl.SSLSession;
+import javax.net.ssl.SSLSocket;
+import javax.net.ssl.SSLSocketFactory;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.TrustManagerFactory;
+import javax.net.ssl.X509KeyManager;
+import javax.net.ssl.X509TrustManager;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.security.KeyManagementException;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.UnrecoverableKeyException;
+import java.security.cert.Certificate;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+
+
+/**
+ * @author Credit Union Central of British Columbia
+ * @author <a href="http://www.cucbc.com/">www.cucbc.com</a>
+ * @author <a href="mailto:juliusdavies@cucbc.com">juliusdavies@cucbc.com</a>
+ * @since 30-Jun-2006
+ */
+public final class Java14 extends JavaImpl {
+ private static Java14 instance = new Java14();
+
+ private Java14() {
+ try {
+ SSLSocketFactory.getDefault().createSocket();
+ } catch (IOException ioe) {
+ ioe.hashCode();
+ }
+ }
+
+ public static Java14 getInstance() {
+ return instance;
+ }
+
+ public String getVersion() {
+ return "Java14";
+ }
+
+ protected String retrieveSubjectX500(X509Certificate cert) {
+ return cert.getSubjectX500Principal().toString();
+ }
+
+ protected String retrieveIssuerX500(X509Certificate cert) {
+ return cert.getIssuerX500Principal().toString();
+ }
+
+ protected Certificate[] retrievePeerCerts(SSLSession sslSession)
+ throws SSLPeerUnverifiedException {
+ return sslSession.getPeerCertificates();
+ }
+
+ protected Object buildKeyManagerFactory(KeyStore ks, char[] password)
+ throws NoSuchAlgorithmException, KeyStoreException,
+ UnrecoverableKeyException {
+ String alg = KeyManagerFactory.getDefaultAlgorithm();
+ KeyManagerFactory kmf = KeyManagerFactory.getInstance(alg);
+ kmf.init(ks, password);
+ return kmf;
+ }
+
+ protected Object buildTrustManagerFactory(KeyStore ks)
+ throws NoSuchAlgorithmException, KeyStoreException {
+ String alg = TrustManagerFactory.getDefaultAlgorithm();
+ TrustManagerFactory tmf = TrustManagerFactory.getInstance(alg);
+ tmf.init(ks);
+ return tmf;
+ }
+
+ protected Object[] retrieveKeyManagers(Object keyManagerFactory) {
+ KeyManagerFactory kmf = (KeyManagerFactory) keyManagerFactory;
+ return kmf.getKeyManagers();
+ }
+
+ protected Object[] retrieveTrustManagers(Object trustManagerFactory) {
+ TrustManagerFactory tmf = (TrustManagerFactory) trustManagerFactory;
+ return tmf.getTrustManagers();
+ }
+
+ protected SSLSocketFactory buildSSLSocketFactory(Object ssl) {
+ return ((SSLContext) ssl).getSocketFactory();
+ }
+
+ protected SSLServerSocketFactory buildSSLServerSocketFactory(Object ssl) {
+ return ((SSLContext) ssl).getServerSocketFactory();
+ }
+
+ protected RuntimeException buildRuntimeException(Exception cause) {
+ return new RuntimeException(cause);
+ }
+
+ protected SSLSocket buildSocket(SSL ssl) throws IOException {
+ SSLSocketFactory sf = ssl.getSSLSocketFactory();
+ SSLSocket s = (SSLSocket) sf.createSocket();
+ ssl.doPreConnectSocketStuff(s);
+ return s;
+ }
+
+ protected SSLSocket buildSocket(SSL ssl, String remoteHost,
+ int remotePort, InetAddress localHost,
+ int localPort, int timeout)
+ throws IOException {
+ SSLSocket s = buildSocket(ssl);
+ s = (SSLSocket) connectSocket(s, null, remoteHost, remotePort,
+ localHost, localPort, timeout, ssl);
+ ssl.doPostConnectSocketStuff(s, remoteHost);
+ return s;
+ }
+
+
+ protected Socket buildPlainSocket(
+ SSL ssl, String remoteHost, int remotePort, InetAddress localHost, int localPort, int timeout
+ ) throws IOException {
+ Socket s = SocketFactory.getDefault().createSocket();
+ ssl.doPreConnectSocketStuff(s);
+ s = connectSocket(
+ s, null, remoteHost, remotePort, localHost, localPort, timeout, ssl
+ );
+ ssl.doPostConnectSocketStuff(s, remoteHost);
+ return s;
+ }
+
+ protected Socket connectSocket(Socket s, SocketFactory sf,
+ String host, int remotePort,
+ InetAddress localHost, int localPort,
+ int timeout, SSL ssl)
+ throws IOException {
+ if (s == null) {
+ if (sf == null) {
+ s = new Socket();
+ } else {
+ s = sf.createSocket();
+ }
+ }
+ host = ssl.dnsOverride(host);
+ InetAddress remoteHost = Util.toInetAddress(host);
+ InetSocketAddress dest = new InetSocketAddress(remoteHost, remotePort);
+ InetSocketAddress src = new InetSocketAddress(localHost, localPort);
+ s.bind(src);
+ s.connect(dest, timeout);
+ return s;
+ }
+
+ protected SSLServerSocket buildServerSocket(SSL ssl)
+ throws IOException {
+ ServerSocket s = ssl.getSSLServerSocketFactory().createServerSocket();
+ SSLServerSocket ss = (SSLServerSocket) s;
+ ssl.doPreConnectServerSocketStuff(ss);
+ return ss;
+ }
+
+ protected void wantClientAuth(Object o, boolean wantClientAuth) {
+ SSLSocket s;
+ SSLServerSocket ss;
+ if (o instanceof SSLSocket) {
+ s = (SSLSocket) o;
+ s.setWantClientAuth(wantClientAuth);
+ } else if (o instanceof SSLServerSocket) {
+ ss = (SSLServerSocket) o;
+ ss.setWantClientAuth(wantClientAuth);
+ } else {
+ throw new ClassCastException("need SSLSocket or SSLServerSocket");
+ }
+ }
+
+ protected void enabledProtocols(Object o, String[] enabledProtocols) {
+ SSLSocket s;
+ SSLServerSocket ss;
+ if (o instanceof SSLSocket) {
+ s = (SSLSocket) o;
+ s.setEnabledProtocols(enabledProtocols);
+ } else if (o instanceof SSLServerSocket) {
+ ss = (SSLServerSocket) o;
+ ss.setEnabledProtocols(enabledProtocols);
+ } else {
+ throw new ClassCastException("need SSLSocket or SSLServerSocket");
+ }
+ }
+
+ protected void checkTrusted(Object trustManager, X509Certificate[] chain,
+ String authType)
+ throws CertificateException {
+ X509TrustManager tm = (X509TrustManager) trustManager;
+ tm.checkServerTrusted(chain, authType);
+ }
+
+ protected Object initSSL(SSL ssl, TrustChain tc, KeyMaterial k)
+ throws NoSuchAlgorithmException, KeyStoreException,
+ CertificateException, KeyManagementException, IOException {
+ SSLContext context = SSLContext.getInstance(ssl.getDefaultProtocol());
+ TrustManager[] trustManagers = null;
+ KeyManager[] keyManagers = null;
+ if (tc != null) {
+ trustManagers = (TrustManager[]) tc.getTrustManagers();
+ }
+ if (k != null) {
+ keyManagers = (KeyManager[]) k.getKeyManagers();
+ }
+ if (keyManagers != null) {
+ for (int i = 0; i < keyManagers.length; i++) {
+ if (keyManagers[i] instanceof X509KeyManager) {
+ X509KeyManager km = (X509KeyManager) keyManagers[i];
+ keyManagers[i] = new Java14KeyManagerWrapper(km, k, ssl);
+ }
+ }
+ }
+ if (trustManagers != null) {
+ for (int i = 0; i < trustManagers.length; i++) {
+ if (trustManagers[i] instanceof X509TrustManager) {
+ X509TrustManager tm = (X509TrustManager) trustManagers[i];
+ trustManagers[i] = new Java14TrustManagerWrapper(tm, tc, ssl);
+ }
+ }
+ }
+ context.init(keyManagers, trustManagers, null);
+ return context;
+ }
+
+
+}
http://git-wip-us.apache.org/repos/asf/directory-kerby/blob/a2c604ee/kerby-pkix/src/main/java/org/apache/commons/ssl/Java14KeyManagerWrapper.java
----------------------------------------------------------------------
diff --git a/kerby-pkix/src/main/java/org/apache/commons/ssl/Java14KeyManagerWrapper.java b/kerby-pkix/src/main/java/org/apache/commons/ssl/Java14KeyManagerWrapper.java
new file mode 100644
index 0000000..baf7d1e
--- /dev/null
+++ b/kerby-pkix/src/main/java/org/apache/commons/ssl/Java14KeyManagerWrapper.java
@@ -0,0 +1,82 @@
+/*
+ * $HeadURL: http://juliusdavies.ca/svn/not-yet-commons-ssl/tags/commons-ssl-0.3.16/src/java/org/apache/commons/ssl/Java14KeyManagerWrapper.java $
+ * $Revision: 121 $
+ * $Date: 2007-11-13 21:26:57 -0800 (Tue, 13 Nov 2007) $
+ *
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+
+package org.apache.commons.ssl;
+
+import javax.net.ssl.X509KeyManager;
+import java.net.Socket;
+import java.security.Principal;
+import java.security.PrivateKey;
+import java.security.cert.X509Certificate;
+
+/**
+ * @author Credit Union Central of British Columbia
+ * @author <a href="http://www.cucbc.com/">www.cucbc.com</a>
+ * @author <a href="mailto:juliusdavies@cucbc.com">juliusdavies@cucbc.com</a>
+ * @since 30-Mar-2006
+ */
+public class Java14KeyManagerWrapper implements X509KeyManager {
+ private final X509KeyManager keyManager;
+ // private final KeyMaterial keyMaterial;
+ // private final SSL ssl;
+
+ public Java14KeyManagerWrapper(X509KeyManager m, KeyMaterial km, SSL h) {
+ this.keyManager = m;
+ // this.keyMaterial = km;
+ // this.ssl = h;
+ }
+
+ public String chooseClientAlias(String[] keyType, Principal[] issuers,
+ Socket socket) {
+ return keyManager.chooseClientAlias(keyType, issuers, socket);
+ }
+
+ public String chooseServerAlias(String keyType, Principal[] issuers,
+ Socket socket) {
+ return keyManager.chooseServerAlias(keyType, issuers, socket);
+ }
+
+ public X509Certificate[] getCertificateChain(String alias) {
+ return keyManager.getCertificateChain(alias);
+ }
+
+ public String[] getClientAliases(String keyType, Principal[] issuers) {
+ return keyManager.getClientAliases(keyType, issuers);
+ }
+
+ public PrivateKey getPrivateKey(String alias) {
+ return keyManager.getPrivateKey(alias);
+ }
+
+ public String[] getServerAliases(String keyType, Principal[] issuers) {
+ return keyManager.getServerAliases(keyType, issuers);
+ }
+}
http://git-wip-us.apache.org/repos/asf/directory-kerby/blob/a2c604ee/kerby-pkix/src/main/java/org/apache/commons/ssl/Java14TrustManagerWrapper.java
----------------------------------------------------------------------
diff --git a/kerby-pkix/src/main/java/org/apache/commons/ssl/Java14TrustManagerWrapper.java b/kerby-pkix/src/main/java/org/apache/commons/ssl/Java14TrustManagerWrapper.java
new file mode 100644
index 0000000..ac0f6bf
--- /dev/null
+++ b/kerby-pkix/src/main/java/org/apache/commons/ssl/Java14TrustManagerWrapper.java
@@ -0,0 +1,131 @@
+/*
+ * $HeadURL: http://juliusdavies.ca/svn/not-yet-commons-ssl/tags/commons-ssl-0.3.16/src/java/org/apache/commons/ssl/Java14TrustManagerWrapper.java $
+ * $Revision: 138 $
+ * $Date: 2008-03-03 23:50:07 -0800 (Mon, 03 Mar 2008) $
+ *
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+
+package org.apache.commons.ssl;
+
+import javax.net.ssl.X509TrustManager;
+import java.security.cert.CertificateException;
+import java.security.cert.CertificateExpiredException;
+import java.security.cert.X509Certificate;
+
+/**
+ * @author Credit Union Central of British Columbia
+ * @author <a href="http://www.cucbc.com/">www.cucbc.com</a>
+ * @author <a href="mailto:juliusdavies@cucbc.com">juliusdavies@cucbc.com</a>
+ * @since 30-Mar-2006
+ */
+public class Java14TrustManagerWrapper implements X509TrustManager {
+ private final X509TrustManager trustManager;
+ private final TrustChain trustChain;
+ private final SSL ssl;
+
+ public Java14TrustManagerWrapper(X509TrustManager m, TrustChain tc, SSL h) {
+ this.trustManager = m;
+ this.trustChain = tc;
+ this.ssl = h;
+ }
+
+ public void checkClientTrusted(X509Certificate[] chain, String authType)
+ throws CertificateException {
+ ssl.setCurrentClientChain(chain);
+ CertificateException ce = null;
+ try {
+ trustManager.checkClientTrusted(chain, authType);
+ } catch (CertificateException e) {
+ ce = e;
+ }
+ testShouldWeThrow(ce, chain);
+ }
+
+ public void checkServerTrusted(X509Certificate[] chain, String authType)
+ throws CertificateException {
+ ssl.setCurrentServerChain(chain);
+ CertificateException ce = null;
+ try {
+ trustManager.checkServerTrusted(chain, authType);
+ } catch (CertificateException e) {
+ ce = e;
+ }
+ testShouldWeThrow(ce, chain);
+ }
+
+ public X509Certificate[] getAcceptedIssuers() {
+ if (trustChain.containsTrustAll()) {
+ // Counter-intuitively, this means we accept all issuers.
+ return new X509Certificate[0];
+ } else {
+ return trustManager.getAcceptedIssuers();
+ }
+ }
+
+ private void testShouldWeThrow(CertificateException checkException,
+ X509Certificate[] chain)
+ throws CertificateException {
+ if (checkException != null) {
+ Throwable root = getRootThrowable(checkException);
+ boolean expiryProblem = root instanceof CertificateExpiredException;
+ if (expiryProblem) {
+ if (ssl.getCheckExpiry()) {
+ // We're expired, and this factory cares.
+ throw checkException;
+ }
+ } else {
+ // Probably the cert isn't trusted. Only let it through if
+ // this factory trusts everything.
+ if (!trustChain.contains(TrustMaterial.TRUST_ALL)) {
+ throw checkException;
+ }
+ }
+ }
+
+ for (int i = 0; i < chain.length; i++) {
+ X509Certificate c = chain[i];
+ if (ssl.getCheckExpiry()) {
+ c.checkValidity();
+ }
+ if (ssl.getCheckCRL()) {
+ Certificates.checkCRL(c);
+ }
+ }
+ }
+
+ private static Throwable getRootThrowable(Throwable t) {
+ if (t == null) {
+ return t;
+ }
+ Throwable cause = t.getCause();
+ while (cause != null && !t.equals(cause)) {
+ t = cause;
+ cause = t.getCause();
+ }
+ return t;
+ }
+}
http://git-wip-us.apache.org/repos/asf/directory-kerby/blob/a2c604ee/kerby-pkix/src/main/java/org/apache/commons/ssl/JavaImpl.java
----------------------------------------------------------------------
diff --git a/kerby-pkix/src/main/java/org/apache/commons/ssl/JavaImpl.java b/kerby-pkix/src/main/java/org/apache/commons/ssl/JavaImpl.java
new file mode 100644
index 0000000..acd995d
--- /dev/null
+++ b/kerby-pkix/src/main/java/org/apache/commons/ssl/JavaImpl.java
@@ -0,0 +1,231 @@
+/*
+ * $HeadURL: http://juliusdavies.ca/svn/not-yet-commons-ssl/tags/commons-ssl-0.3.16/src/java/org/apache/commons/ssl/JavaImpl.java $
+ * $Revision: 155 $
+ * $Date: 2009-09-17 14:00:58 -0700 (Thu, 17 Sep 2009) $
+ *
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+
+package org.apache.commons.ssl;
+
+import javax.net.SocketFactory;
+import javax.net.ssl.SSLPeerUnverifiedException;
+import javax.net.ssl.SSLServerSocket;
+import javax.net.ssl.SSLServerSocketFactory;
+import javax.net.ssl.SSLSession;
+import javax.net.ssl.SSLSocket;
+import javax.net.ssl.SSLSocketFactory;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.Socket;
+import java.security.KeyManagementException;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.UnrecoverableKeyException;
+import java.security.cert.Certificate;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+
+/**
+ * @author Credit Union Central of British Columbia
+ * @author <a href="http://www.cucbc.com/">www.cucbc.com</a>
+ * @author <a href="mailto:juliusdavies@cucbc.com">juliusdavies@cucbc.com</a>
+ * @since 30-Jun-2006
+ */
+public abstract class JavaImpl {
+ private static JavaImpl handler;
+
+ static {
+ JavaImpl h = null;
+ h = Java14.getInstance();
+ handler = h;
+ }
+
+ public abstract String getVersion();
+
+ protected abstract Object buildKeyManagerFactory(KeyStore ks, char[] pass)
+ throws NoSuchAlgorithmException, KeyStoreException,
+ UnrecoverableKeyException;
+
+ protected abstract Object[] retrieveKeyManagers(Object keyManagerFactory);
+
+ protected abstract Object buildTrustManagerFactory(KeyStore ks)
+ throws NoSuchAlgorithmException, KeyStoreException;
+
+ protected abstract Object[] retrieveTrustManagers(Object trustManagerFactory);
+
+ protected abstract String retrieveSubjectX500(X509Certificate cert);
+
+ protected abstract String retrieveIssuerX500(X509Certificate cert);
+
+ protected abstract Certificate[] retrievePeerCerts(SSLSession sslSession)
+ throws SSLPeerUnverifiedException;
+
+ protected abstract SSLSocketFactory buildSSLSocketFactory(Object ssl);
+
+ protected abstract SSLServerSocketFactory buildSSLServerSocketFactory(Object ssl);
+
+ protected abstract SSLSocket buildSocket(SSL ssl)
+ throws IOException;
+
+ protected abstract SSLSocket buildSocket(
+ SSL ssl, String remoteHost, int remotePort, InetAddress localHost, int localPort, int connectTimeout
+ ) throws IOException;
+
+ protected abstract Socket buildPlainSocket(
+ SSL ssl, String remoteHost, int remotePort, InetAddress localHost, int localPort, int connectTimeout
+ ) throws IOException;
+
+ protected abstract Socket connectSocket(Socket s, SocketFactory sf,
+ String remoteHost, int remotePort,
+ InetAddress localHost, int localPort,
+ int timeout, SSL ssl)
+ throws IOException;
+
+ protected abstract SSLServerSocket buildServerSocket(SSL ssl)
+ throws IOException;
+
+ protected abstract void wantClientAuth(Object o, boolean wantClientAuth);
+
+ protected abstract void enabledProtocols(Object o, String[] enabledProtocols);
+
+ protected abstract RuntimeException buildRuntimeException(Exception cause);
+
+ protected abstract Object initSSL(SSL ssl, TrustChain tc, KeyMaterial km)
+ throws NoSuchAlgorithmException, KeyStoreException,
+ CertificateException, KeyManagementException, IOException;
+
+ protected abstract void checkTrusted(Object trustManager,
+ X509Certificate[] chain,
+ String authType)
+ throws CertificateException;
+
+ public static Object init(SSL ssl, TrustChain trustChain, KeyMaterial keyMaterial)
+ throws NoSuchAlgorithmException, KeyStoreException,
+ CertificateException, KeyManagementException, IOException {
+ return handler.initSSL(ssl, trustChain, keyMaterial);
+ }
+
+ public static RuntimeException newRuntimeException(Exception cause) {
+ return handler.buildRuntimeException(cause);
+ }
+
+ public static SSLSocketFactory getSSLSocketFactory(Object sslContext) {
+ return handler.buildSSLSocketFactory(sslContext);
+ }
+
+ public static SSLServerSocketFactory getSSLServerSocketFactory(Object sslContext) {
+ return handler.buildSSLServerSocketFactory(sslContext);
+ }
+
+ public static String getSubjectX500(X509Certificate cert) {
+ return handler.retrieveSubjectX500(cert);
+ }
+
+ public static String getIssuerX500(X509Certificate cert) {
+ return handler.retrieveIssuerX500(cert);
+ }
+
+ public static Object newKeyManagerFactory(KeyStore ks, char[] password)
+ throws NoSuchAlgorithmException, KeyStoreException,
+ UnrecoverableKeyException {
+ return handler.buildKeyManagerFactory(ks, password);
+ }
+
+ public static Object[] getKeyManagers(Object keyManagerFactory) {
+ return handler.retrieveKeyManagers(keyManagerFactory);
+ }
+
+ public static Object newTrustManagerFactory(KeyStore ks)
+ throws NoSuchAlgorithmException, KeyStoreException {
+ return handler.buildTrustManagerFactory(ks);
+ }
+
+ public static Object[] getTrustManagers(Object trustManagerFactory) {
+ return handler.retrieveTrustManagers(trustManagerFactory);
+ }
+
+ public static SSLSocket createSocket(SSL ssl)
+ throws IOException {
+ return handler.buildSocket(ssl);
+ }
+
+ public static SSLSocket createSocket(SSL ssl, String remoteHost,
+ int remotePort, InetAddress localHost,
+ int localPort, int connectTimeout)
+ throws IOException {
+ return handler.buildSocket(ssl, remoteHost, remotePort, localHost,
+ localPort, connectTimeout);
+ }
+
+ public static Socket createPlainSocket(
+ SSL ssl, String remoteHost, int remotePort, InetAddress localHost, int localPort,
+ int connectTimeout
+ ) throws IOException {
+ return handler.buildPlainSocket(
+ ssl, remoteHost, remotePort, localHost, localPort, connectTimeout
+ );
+ }
+
+ protected static Socket connect(Socket s, SocketFactory sf,
+ String remoteHost, int remotePort,
+ InetAddress localHost, int localPort,
+ int timeout, SSL ssl)
+ throws IOException {
+ return handler.connectSocket(s, sf, remoteHost, remotePort, localHost,
+ localPort, timeout, ssl);
+ }
+
+ public static SSLServerSocket createServerSocket(SSL ssl)
+ throws IOException {
+ return handler.buildServerSocket(ssl);
+ }
+
+ public static void setWantClientAuth(Object o, boolean wantClientAuth) {
+ handler.wantClientAuth(o, wantClientAuth);
+ }
+
+ public static void setEnabledProtocols(Object o, String[] enabledProtocols) {
+ handler.enabledProtocols(o, enabledProtocols);
+ }
+
+ public static Certificate[] getPeerCertificates(SSLSession session)
+ throws SSLPeerUnverifiedException {
+ return handler.retrievePeerCerts(session);
+ }
+
+ public static void testTrust(Object trustManager, X509Certificate[] chain,
+ String authType)
+ throws CertificateException {
+ handler.checkTrusted(trustManager, chain, authType);
+ }
+
+ public static void load() {
+ handler.hashCode();
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/directory-kerby/blob/a2c604ee/kerby-pkix/src/main/java/org/apache/commons/ssl/KeyMaterial.java
----------------------------------------------------------------------
diff --git a/kerby-pkix/src/main/java/org/apache/commons/ssl/KeyMaterial.java b/kerby-pkix/src/main/java/org/apache/commons/ssl/KeyMaterial.java
new file mode 100644
index 0000000..0ec2040
--- /dev/null
+++ b/kerby-pkix/src/main/java/org/apache/commons/ssl/KeyMaterial.java
@@ -0,0 +1,292 @@
+/*
+ * $HeadURL: http://juliusdavies.ca/svn/not-yet-commons-ssl/tags/commons-ssl-0.3.16/src/java/org/apache/commons/ssl/KeyMaterial.java $
+ * $Revision: 138 $
+ * $Date: 2008-03-03 23:50:07 -0800 (Mon, 03 Mar 2008) $
+ *
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+
+package org.apache.commons.ssl;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.security.GeneralSecurityException;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.cert.Certificate;
+import java.security.cert.CertificateEncodingException;
+import java.security.cert.X509Certificate;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+
+/**
+ * @author Credit Union Central of British Columbia
+ * @author <a href="http://www.cucbc.com/">www.cucbc.com</a>
+ * @author <a href="mailto:juliusdavies@cucbc.com">juliusdavies@cucbc.com</a>
+ * @since 27-Feb-2006
+ */
+public class KeyMaterial extends TrustMaterial {
+ private final Object keyManagerFactory;
+ private final List aliases;
+ private final List associatedChains;
+
+ public KeyMaterial(InputStream jks, char[] password)
+ throws GeneralSecurityException, IOException {
+ this(Util.streamToBytes(jks), password);
+ }
+
+ public KeyMaterial(InputStream jks, char[] jksPass, char[] keyPass)
+ throws GeneralSecurityException, IOException {
+ this(Util.streamToBytes(jks), jksPass, keyPass);
+ }
+
+ public KeyMaterial(InputStream jks, InputStream key, char[] password)
+ throws GeneralSecurityException, IOException {
+ this(jks != null ? Util.streamToBytes(jks) : null,
+ key != null ? Util.streamToBytes(key) : null,
+ password);
+ }
+
+ public KeyMaterial(InputStream jks, InputStream key, char[] jksPass,
+ char[] keyPass)
+ throws GeneralSecurityException, IOException {
+ this(jks != null ? Util.streamToBytes(jks) : null,
+ key != null ? Util.streamToBytes(key) : null,
+ jksPass, keyPass);
+ }
+
+ public KeyMaterial(String pathToJksFile, char[] password)
+ throws GeneralSecurityException, IOException {
+ this(new File(pathToJksFile), password);
+ }
+
+ public KeyMaterial(String pathToJksFile, char[] jksPass, char[] keyPass)
+ throws GeneralSecurityException, IOException {
+ this(new File(pathToJksFile), jksPass, keyPass);
+ }
+
+ public KeyMaterial(String pathToCerts, String pathToKey, char[] password)
+ throws GeneralSecurityException, IOException {
+ this(pathToCerts != null ? new File(pathToCerts) : null,
+ pathToKey != null ? new File(pathToKey) : null,
+ password);
+ }
+
+ public KeyMaterial(String pathToCerts, String pathToKey, char[] jksPass,
+ char[] keyPass)
+ throws GeneralSecurityException, IOException {
+ this(pathToCerts != null ? new File(pathToCerts) : null,
+ pathToKey != null ? new File(pathToKey) : null,
+ jksPass, keyPass);
+ }
+
+ public KeyMaterial(File jksFile, char[] password)
+ throws GeneralSecurityException, IOException {
+ this(new FileInputStream(jksFile), password);
+ }
+
+ public KeyMaterial(File jksFile, char[] jksPass, char[] keyPass)
+ throws GeneralSecurityException, IOException {
+ this(new FileInputStream(jksFile), jksPass, keyPass);
+ }
+
+ public KeyMaterial(File certsFile, File keyFile, char[] password)
+ throws GeneralSecurityException, IOException {
+ this(certsFile != null ? new FileInputStream(certsFile) : null,
+ keyFile != null ? new FileInputStream(keyFile) : null,
+ password);
+ }
+
+ public KeyMaterial(File certsFile, File keyFile, char[] jksPass,
+ char[] keyPass)
+ throws GeneralSecurityException, IOException {
+ this(certsFile != null ? new FileInputStream(certsFile) : null,
+ keyFile != null ? new FileInputStream(keyFile) : null,
+ jksPass, keyPass);
+ }
+
+ public KeyMaterial(URL urlToJKS, char[] password)
+ throws GeneralSecurityException, IOException {
+ this(urlToJKS.openStream(), password);
+ }
+
+ public KeyMaterial(URL urlToJKS, char[] jksPass, char[] keyPass)
+ throws GeneralSecurityException, IOException {
+ this(urlToJKS.openStream(), jksPass, keyPass);
+ }
+
+ public KeyMaterial(URL urlToCerts, URL urlToKey, char[] password)
+ throws GeneralSecurityException, IOException {
+ this(urlToCerts.openStream(), urlToKey.openStream(), password);
+ }
+
+ public KeyMaterial(URL urlToCerts, URL urlToKey, char[] jksPass,
+ char[] keyPass)
+ throws GeneralSecurityException, IOException {
+ this(urlToCerts.openStream(), urlToKey.openStream(), jksPass, keyPass);
+ }
+
+ public KeyMaterial(byte[] jks, char[] password)
+ throws GeneralSecurityException, IOException {
+ this(jks, (byte[]) null, password);
+ }
+
+ public KeyMaterial(byte[] jks, char[] jksPass, char[] keyPass)
+ throws GeneralSecurityException, IOException {
+ this(jks, null, jksPass, keyPass);
+ }
+
+ public KeyMaterial(byte[] jksOrCerts, byte[] key, char[] password)
+ throws GeneralSecurityException, IOException {
+ this(jksOrCerts, key, password, password);
+ }
+
+
+ public KeyMaterial(byte[] jksOrCerts, byte[] key, char[] jksPass,
+ char[] keyPass)
+ throws GeneralSecurityException, IOException {
+ // We're not a simple trust type, so set "simpleTrustType" value to 0.
+ // Only TRUST_ALL and TRUST_THIS_JVM are simple trust types.
+ super(KeyStoreBuilder.build(jksOrCerts, key, jksPass, keyPass), 0);
+ KeyStore ks = getKeyStore();
+ Enumeration en = ks.aliases();
+ List myAliases = new LinkedList();
+ List myChains = new LinkedList();
+ while (en.hasMoreElements()) {
+ X509Certificate[] c; // chain
+ String alias = (String) en.nextElement();
+ if (ks.isKeyEntry(alias)) {
+ try {
+ ks.getKey(alias, keyPass);
+ // No Exception thrown, so we're good!
+ myAliases.add(alias);
+ Certificate[] chain = ks.getCertificateChain(alias);
+ if (chain != null) {
+ c = Certificates.x509ifyChain(chain);
+ // Cleanup chain to remove any spurious entries.
+ if (c != null) {
+ X509Certificate l = c[0]; // The leaf node.
+ c = X509CertificateChainBuilder.buildPath(l, c);
+ }
+ myChains.add(c);
+ } else {
+ throw new KeyStoreException("Could not find KeyMaterial's"
+ + " associated certificate chain with alis=[" + alias + "]");
+ }
+
+ } catch (GeneralSecurityException gse) {
+ // oh well, we can't use that KeyStore alias.
+ System.err.println(gse);
+ }
+ }
+ }
+ if (myAliases.isEmpty()) {
+ throw new KeyStoreException("KeyMaterial provided does not contain any keys!");
+ }
+ this.aliases = Collections.unmodifiableList(myAliases);
+ this.associatedChains = Collections.unmodifiableList(myChains);
+ this.keyManagerFactory = JavaImpl.newKeyManagerFactory(ks, keyPass);
+ }
+
+ public Object[] getKeyManagers() {
+ return JavaImpl.getKeyManagers(keyManagerFactory);
+ }
+
+ public List getAssociatedCertificateChains() {
+ return associatedChains;
+ }
+
+ public KeyStore getKeyStore() {
+ return super.getKeyStore();
+ }
+
+ public List getAliases() {
+ return aliases;
+ }
+
+ public static void main(String[] args) throws Exception {
+ if (args.length < 2) {
+ System.out.println("Usage1:"
+ + " java org.apache.commons.ssl.KeyMaterial [password] [pkcs12 or jks]");
+ System.out.println("Usage2:"
+ + " java org.apache.commons.ssl.KeyMaterial [password] [private-key] [cert-chain]");
+ System.exit(1);
+ }
+ char[] jksPass = args[0].toCharArray();
+ char[] keyPass = jksPass;
+ String path1 = args[1];
+ String path2 = null;
+ if (args.length >= 3) {
+ path2 = args[2];
+ }
+ if (args.length >= 4) {
+ keyPass = args[3].toCharArray();
+ } else if (path2 != null) {
+ File f = new File(path2);
+ if (!f.exists()) {
+ // Hmmm... maybe it's a password.
+ keyPass = path2.toCharArray();
+ path2 = null;
+ }
+ }
+
+ KeyMaterial km = new KeyMaterial(path1, path2, jksPass, keyPass);
+ System.out.println(km);
+ }
+
+ public String toString() {
+ List chains = getAssociatedCertificateChains();
+ List aliases = getAliases();
+ Iterator it = chains.iterator();
+ Iterator aliasesIt = aliases.iterator();
+ StringBuffer buf = new StringBuffer(8192);
+ while (it.hasNext()) {
+ X509Certificate[] certs = (X509Certificate[]) it.next();
+ String alias = (String) aliasesIt.next();
+ buf.append("Alias: ");
+ buf.append(alias);
+ buf.append('\n');
+ if (certs != null) {
+ for (int i = 0; i < certs.length; i++) {
+ buf.append(Certificates.toString(certs[i]));
+ try {
+ buf.append(Certificates.toPEMString(certs[i]));
+ } catch (CertificateEncodingException cee) {
+ buf.append(cee.toString());
+ buf.append('\n');
+ }
+ }
+ }
+ }
+ return buf.toString();
+ }
+}
http://git-wip-us.apache.org/repos/asf/directory-kerby/blob/a2c604ee/kerby-pkix/src/main/java/org/apache/commons/ssl/KeyStoreBuilder.java
----------------------------------------------------------------------
diff --git a/kerby-pkix/src/main/java/org/apache/commons/ssl/KeyStoreBuilder.java b/kerby-pkix/src/main/java/org/apache/commons/ssl/KeyStoreBuilder.java
new file mode 100644
index 0000000..828b99d
--- /dev/null
+++ b/kerby-pkix/src/main/java/org/apache/commons/ssl/KeyStoreBuilder.java
@@ -0,0 +1,693 @@
+/*
+ * $HeadURL: http://juliusdavies.ca/svn/not-yet-commons-ssl/tags/commons-ssl-0.3.16/src/java/org/apache/commons/ssl/KeyStoreBuilder.java $
+ * $Revision: 180 $
+ * $Date: 2014-09-23 11:33:47 -0700 (Tue, 23 Sep 2014) $
+ *
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+
+package org.apache.commons.ssl;
+
+import org.apache.kerby.asn1.type.Asn1Integer;
+import org.apache.kerby.asn1.type.Asn1Sequence;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.math.BigInteger;
+import java.security.GeneralSecurityException;
+import java.security.InvalidKeyException;
+import java.security.Key;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+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.DSAParams;
+import java.security.interfaces.DSAPrivateKey;
+import java.security.interfaces.RSAPrivateCrtKey;
+import java.security.interfaces.RSAPublicKey;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+
+/**
+ * Builds Java Key Store files out of pkcs12 files, or out of pkcs8 files +
+ * certificate chains. Also supports OpenSSL style private keys (encrypted or
+ * unencrypted).
+ *
+ * @author Credit Union Central of British Columbia
+ * @author <a href="http://www.cucbc.com/">www.cucbc.com</a>
+ * @author <a href="mailto:juliusdavies@cucbc.com">juliusdavies@cucbc.com</a>
+ * @since 4-Nov-2006
+ */
+public class KeyStoreBuilder {
+ private static final String PKCS7_ENCRYPTED = "1.2.840.113549.1.7.6";
+
+ public static KeyStore build(byte[] jksOrCerts, char[] password)
+ throws IOException, CertificateException, KeyStoreException,
+ NoSuchAlgorithmException, InvalidKeyException,
+ NoSuchProviderException, ProbablyBadPasswordException,
+ UnrecoverableKeyException {
+ return build(jksOrCerts, null, password);
+ }
+
+ public static KeyStore build(byte[] jksOrCerts, byte[] privateKey,
+ char[] password)
+ throws IOException, CertificateException, KeyStoreException,
+ NoSuchAlgorithmException, InvalidKeyException,
+ NoSuchProviderException, ProbablyBadPasswordException,
+ UnrecoverableKeyException {
+ return build(jksOrCerts, privateKey, password, null);
+ }
+
+
+ public static KeyStore build(byte[] jksOrCerts, byte[] privateKey,
+ char[] jksPassword, char[] keyPassword)
+ throws IOException, CertificateException, KeyStoreException,
+ NoSuchAlgorithmException, InvalidKeyException,
+ NoSuchProviderException, ProbablyBadPasswordException,
+ UnrecoverableKeyException {
+
+ if (keyPassword == null || keyPassword.length <= 0) {
+ keyPassword = jksPassword;
+ }
+
+ BuildResult br1 = parse(jksOrCerts, jksPassword, keyPassword);
+ BuildResult br2 = null;
+ KeyStore jks = null;
+ if (br1.jks != null) {
+ jks = br1.jks;
+ } else if (privateKey != null && privateKey.length > 0) {
+ br2 = parse(privateKey, jksPassword, keyPassword);
+ if (br2.jks != null) {
+ jks = br2.jks;
+ }
+ }
+
+ // If we happened to find a JKS file, let's just return that.
+ // JKS files get priority (in case some weirdo specifies both a PKCS12
+ // and a JKS file!).
+ if (jks != null) {
+ // Make sure the keystore we found is not corrupt.
+ br1 = validate(jks, keyPassword);
+ if (br1 == null) {
+ return jks;
+ }
+ }
+
+ List keys = br1.keys;
+ List chains = br1.chains;
+ boolean atLeastOneNotSet = keys == null || chains == null || keys.isEmpty() || chains.isEmpty();
+ if (atLeastOneNotSet && br2 != null) {
+ if (br2.keys != null && !br2.keys.isEmpty()) {
+ // Notice that the key from build-result-2 gets priority over the
+ // key from build-result-1 (if both had valid keys).
+ keys = br2.keys;
+ }
+ if (chains == null || chains.isEmpty()) {
+ chains = br2.chains;
+ }
+ }
+
+ atLeastOneNotSet = keys == null || chains == null || keys.isEmpty() || chains.isEmpty();
+ if (atLeastOneNotSet) {
+ String missing = "";
+ if (keys == null) {
+ missing = " [Private key missing (bad password?)]";
+ }
+ if (chains == null) {
+ missing += " [Certificate chain missing]";
+ }
+ throw new KeyStoreException("Can't build keystore:" + missing);
+ } else {
+ KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
+ ks.load(null, jksPassword);
+ Iterator keysIt = keys.iterator();
+ Iterator chainsIt = chains.iterator();
+ int i = 1;
+ while (keysIt.hasNext() && chainsIt.hasNext()) {
+ Key key = (Key) keysIt.next();
+ Certificate[] c = (Certificate[]) chainsIt.next();
+ X509Certificate theOne = buildChain(key, c);
+ String alias = "alias_" + i++;
+ // The theOne is not null, then our chain was probably altered.
+ // Need to trim out the newly introduced null entries at the end of
+ // our chain.
+ if (theOne != null) {
+ c = Certificates.trimChain(c);
+ alias = Certificates.getCN(theOne);
+ alias = alias.replace(' ', '_');
+ }
+ ks.setKeyEntry(alias, key, keyPassword, c);
+ }
+ return ks;
+ }
+ }
+
+ /**
+ * Builds the chain up such that chain[ 0 ] contains the public key
+ * corresponding to the supplied private key.
+ *
+ * @param key private key
+ * @param chain array of certificates to build chain from
+ * @return theOne!
+ * @throws java.security.KeyStoreException no certificates correspond to private key
+ * @throws java.security.cert.CertificateException java libraries complaining
+ * @throws java.security.NoSuchAlgorithmException java libraries complaining
+ * @throws java.security.InvalidKeyException java libraries complaining
+ * @throws java.security.NoSuchProviderException java libraries complaining
+ */
+ public static X509Certificate buildChain(Key key, Certificate[] chain)
+ throws CertificateException, KeyStoreException,
+ NoSuchAlgorithmException, InvalidKeyException,
+ NoSuchProviderException {
+ X509Certificate theOne = null;
+ if (key instanceof RSAPrivateCrtKey) {
+ final RSAPrivateCrtKey rsa = (RSAPrivateCrtKey) key;
+ BigInteger publicExponent = rsa.getPublicExponent();
+ BigInteger modulus = rsa.getModulus();
+ for (int i = 0; i < chain.length; i++) {
+ X509Certificate c = (X509Certificate) chain[i];
+ PublicKey pub = c.getPublicKey();
+ if (pub instanceof RSAPublicKey) {
+ RSAPublicKey certKey = (RSAPublicKey) pub;
+ BigInteger pe = certKey.getPublicExponent();
+ BigInteger mod = certKey.getModulus();
+ if (publicExponent.equals(pe) && modulus.equals(mod)) {
+ theOne = c;
+ }
+ }
+ }
+ if (theOne == null) {
+ throw new KeyStoreException("Can't build keystore: [No certificates belong to the private-key]");
+ }
+ X509Certificate[] newChain;
+ newChain = X509CertificateChainBuilder.buildPath(theOne, chain);
+ Arrays.fill(chain, null);
+ System.arraycopy(newChain, 0, chain, 0, newChain.length);
+ }
+ return theOne;
+ }
+
+ public static BuildResult validate(KeyStore jks, char[] keyPass)
+ throws CertificateException, KeyStoreException,
+ NoSuchAlgorithmException, InvalidKeyException,
+ NoSuchProviderException, UnrecoverableKeyException {
+ Enumeration en = jks.aliases();
+ boolean atLeastOneSuccess = false;
+ boolean atLeastOneFailure = false;
+
+ List keys = new LinkedList();
+ List chains = new LinkedList();
+ while (en.hasMoreElements()) {
+ String alias = (String) en.nextElement();
+ if (jks.isKeyEntry(alias)) {
+ try {
+ PrivateKey key = (PrivateKey) jks.getKey(alias, keyPass);
+ // No Exception thrown, so we're good!
+ atLeastOneSuccess = true;
+ Certificate[] chain = jks.getCertificateChain(alias);
+ X509Certificate[] c;
+ if (chain != null) {
+ c = Certificates.x509ifyChain(chain);
+ X509Certificate theOne = buildChain(key, c);
+ // The theOne is not null, then our chain was probably
+ // altered. Need to trim out the newly introduced null
+ // entries at the end of our chain.
+ if (theOne != null) {
+ c = (X509Certificate[]) Certificates.trimChain(c);
+ jks.deleteEntry(alias);
+ jks.setKeyEntry(alias, key, keyPass, c);
+ }
+ keys.add(key);
+ chains.add(c);
+ }
+ } catch (GeneralSecurityException gse) {
+ atLeastOneFailure = true;
+ // This is not the key you're looking for.
+ }
+ }
+ }
+ if (!atLeastOneSuccess) {
+ throw new KeyStoreException("No private keys found in keystore!");
+ }
+ // The idea is a bit hacky: if we return null, all is cool. If
+ // we return a list, we're telling upstairs to abandon the JKS and
+ // build a new one from the BuildResults we provide.
+ // (Sun's builtin SSL refuses to deal with keystores where not all
+ // keys can be decrypted).
+ return atLeastOneFailure ? new BuildResult(keys, chains, null) : null;
+ }
+
+ public static class BuildResult {
+ protected final List keys;
+ protected final List chains;
+ protected final KeyStore jks;
+
+ protected BuildResult(List keys, List chains, KeyStore jks) {
+ if (keys == null || keys.isEmpty()) {
+ this.keys = null;
+ } else {
+ this.keys = Collections.unmodifiableList(keys);
+ }
+ this.jks = jks;
+ List x509Chains = new LinkedList();
+ if (chains != null) {
+ Iterator it = chains.iterator();
+ while (it.hasNext()) {
+ Certificate[] chain = (Certificate[]) it.next();
+ if (chain != null && chain.length > 0) {
+ int len = chain.length;
+ X509Certificate[] x509 = new X509Certificate[len];
+ for (int i = 0; i < x509.length; i++) {
+ x509[i] = (X509Certificate) chain[i];
+ }
+ x509Chains.add(x509);
+ }
+ }
+ }
+ if (x509Chains == null || x509Chains.isEmpty()) {
+ this.chains = null;
+ } else {
+ this.chains = Collections.unmodifiableList(x509Chains);
+ }
+ }
+ }
+
+
+ public static BuildResult parse(byte[] stuff, char[] jksPass,
+ char[] keyPass)
+ throws IOException, CertificateException, KeyStoreException,
+ ProbablyBadPasswordException {
+
+ return parse(stuff, jksPass, keyPass, false);
+ }
+
+ static BuildResult parse(byte[] stuff, char[] jksPass,
+ char[] keyPass, boolean forTrustMaterial)
+ throws IOException, CertificateException, KeyStoreException,
+ ProbablyBadPasswordException {
+ CertificateFactory cf = CertificateFactory.getInstance("X.509");
+ Key key = null;
+ Certificate[] chain = null;
+ try {
+ PKCS8Key pkcs8Key = new PKCS8Key(stuff, jksPass);
+ key = pkcs8Key.getPrivateKey();
+ } catch (ProbablyBadPasswordException pbpe) {
+ throw pbpe;
+ } catch (GeneralSecurityException gse) {
+ // no luck
+ System.err.println(gse);
+ }
+
+ List pemItems = PEMUtil.decode(stuff);
+ Iterator it = pemItems.iterator();
+ LinkedList certificates = new LinkedList();
+ while (it.hasNext()) {
+ PEMItem item = (PEMItem) it.next();
+ byte[] derBytes = item.getDerBytes();
+ String type = item.pemType.trim().toUpperCase();
+ if (type.startsWith("CERT")
+ || type.startsWith("X509")
+ || type.startsWith("PKCS7")) {
+ ByteArrayInputStream in = new ByteArrayInputStream(derBytes);
+ X509Certificate c = (X509Certificate) cf.generateCertificate(in);
+ certificates.add(c);
+ }
+ chain = toChain(certificates);
+ }
+
+ if (chain != null || key != null) {
+ List chains = chain != null ? Collections.singletonList(chain) : null;
+ List keys = key != null ? Collections.singletonList(key) : null;
+ return new BuildResult(keys, chains, null);
+ }
+
+ boolean isProbablyPKCS12 = false;
+ boolean isASN = false;
+ Asn1PkcsStructure asn1 = null;
+ try {
+ asn1 = Asn1PkcsUtil.analyze(stuff);
+ isASN = true;
+ isProbablyPKCS12 = asn1.oids.contains(PKCS7_ENCRYPTED);
+ if (!isProbablyPKCS12 && asn1.bigPayload != null) {
+ asn1 = Asn1PkcsUtil.analyze(asn1.bigPayload);
+ isProbablyPKCS12 = asn1.oids.contains(PKCS7_ENCRYPTED);
+ }
+ } catch (Exception e) {
+ // isProbablyPKCS12 and isASN are set properly by now.
+ System.err.println(e);
+ }
+
+ ByteArrayInputStream stuffStream = new ByteArrayInputStream(stuff);
+ // Try default keystore... then try others.
+ BuildResult br = tryJKS(KeyStore.getDefaultType(), stuffStream, jksPass, keyPass, forTrustMaterial);
+ if (br == null) {
+ br = tryJKS("jks", stuffStream, jksPass, keyPass, forTrustMaterial);
+ if (br == null) {
+ br = tryJKS("jceks", stuffStream, jksPass, keyPass, forTrustMaterial);
+ if (br == null) {
+ br = tryJKS("BKS", stuffStream, jksPass, keyPass, forTrustMaterial);
+ if (br == null) {
+ br = tryJKS("UBER", stuffStream, jksPass, keyPass, forTrustMaterial);
+ }
+ }
+ }
+ }
+ if (br != null) {
+ return br;
+ }
+ if (isASN && isProbablyPKCS12) {
+ br = tryJKS("pkcs12", stuffStream, jksPass, null, forTrustMaterial);
+ }
+
+ if (br == null) {
+ // Okay, it's ASN.1, but it's not PKCS12. Only one possible
+ // interesting things remains: X.509.
+ stuffStream.reset();
+
+ try {
+ certificates = new LinkedList();
+ Collection certs = cf.generateCertificates(stuffStream);
+ it = certs.iterator();
+ while (it.hasNext()) {
+ X509Certificate x509 = (X509Certificate) it.next();
+ certificates.add(x509);
+ }
+ chain = toChain(certificates);
+ if (chain != null && chain.length > 0) {
+ List chains = Collections.singletonList(chain);
+ return new BuildResult(null, chains, null);
+ }
+ } catch (CertificateException ce) {
+ // oh well
+ System.err.println(ce);
+ }
+
+ stuffStream.reset();
+ // Okay, still no luck. Maybe it's an ASN.1 DER stream
+ // containing only a single certificate? (I don't completely
+ // trust CertificateFactory.generateCertificates).
+ try {
+ Certificate c = cf.generateCertificate(stuffStream);
+ X509Certificate x509 = (X509Certificate) c;
+ chain = toChain(Collections.singleton(x509));
+ if (chain != null && chain.length > 0) {
+ List chains = Collections.singletonList(chain);
+ return new BuildResult(null, chains, null);
+ }
+ } catch (CertificateException ce) {
+ // oh well
+ System.err.println(ce);
+ }
+ }
+
+ br = tryJKS("pkcs12", stuffStream, jksPass, null, forTrustMaterial);
+ if (br != null) {
+ // no exception thrown, so must be PKCS12.
+ /*
+ Hmm, well someone finally reported this bug! And they want the library to be quiet....
+ Commenting out for now, maybe investigate why it's happening one day....
+
+ System.out.println("Please report bug!");
+ System.out.println("PKCS12 detection failed to realize this was PKCS12!");
+ System.out.println(asn1);
+ */
+ return br;
+ }
+ throw new KeyStoreException("failed to extract any certificates or private keys - maybe bad password?");
+ }
+
+ private static BuildResult tryJKS(
+ String keystoreType, ByteArrayInputStream in, char[] jksPassword, char[] keyPassword,
+ boolean forTrustMaterial
+ ) throws ProbablyBadPasswordException {
+ in.reset();
+ if (keyPassword == null || keyPassword.length <= 0) {
+ keyPassword = jksPassword;
+ }
+
+ keystoreType = keystoreType.trim().toLowerCase();
+ boolean isPKCS12 = "pkcs12".equalsIgnoreCase(keystoreType);
+ try {
+ Key key = null;
+ Certificate[] chain = null;
+ UnrecoverableKeyException uke = null;
+ KeyStore jksKeyStore = KeyStore.getInstance(keystoreType);
+ jksKeyStore.load(in, jksPassword);
+ Enumeration en = jksKeyStore.aliases();
+ while (en.hasMoreElements()) {
+ String alias = (String) en.nextElement();
+ if (jksKeyStore.isKeyEntry(alias)) {
+ try {
+ if (keyPassword != null) {
+ key = jksKeyStore.getKey(alias, keyPassword);
+ }
+ if (key instanceof PrivateKey) {
+ chain = jksKeyStore.getCertificateChain(alias);
+ break;
+ }
+ } catch (UnrecoverableKeyException e) {
+ uke = e; // We might throw this one later.
+ } catch (GeneralSecurityException gse) {
+ // Swallow... keep looping.
+ System.err.println(gse);
+ }
+ }
+ if (isPKCS12 && en.hasMoreElements()) {
+ System.out.println("what kind of weird pkcs12 file has more than one alias?");
+ }
+ }
+ if (key == null && uke != null) {
+ // If we're trying to load KeyMaterial, then we *need* that key we spotted.
+ // But if we're trying to load TrustMaterial, then we're fine, and we can ignore the key.
+ if (!forTrustMaterial) {
+ throw new ProbablyBadPasswordException("Probably bad JKS-Key password: " + uke);
+ }
+ }
+ if (isPKCS12) {
+ // PKCS12 is supposed to be just a key and a chain, anyway.
+ jksKeyStore = null;
+ }
+
+ List keys = Collections.singletonList(key);
+ List chains = Collections.singletonList(chain);
+ return new BuildResult(keys, chains, jksKeyStore);
+ } catch (ProbablyBadPasswordException pbpe) {
+ throw pbpe;
+ } catch (GeneralSecurityException gse) {
+ // swallow it, return null
+ return null;
+ } catch (IOException ioe) {
+ String msg = ioe.getMessage();
+ msg = msg != null ? msg.trim().toLowerCase() : "";
+ if (isPKCS12) {
+ int x = msg.indexOf("failed to decrypt");
+ int y = msg.indexOf("verify mac");
+ x = Math.max(x, y);
+ if (x >= 0) {
+ throw new ProbablyBadPasswordException("Probably bad PKCS12 password: " + ioe);
+ }
+ } else {
+ int x = msg.indexOf("password");
+ if (x >= 0) {
+ throw new ProbablyBadPasswordException("Probably bad JKS password: " + ioe);
+ }
+ }
+ // swallow it, return null.
+ return null;
+ }
+ }
+
+ private static X509Certificate[] toChain(Collection certs) {
+ if (certs != null && !certs.isEmpty()) {
+ X509Certificate[] x509Chain = new X509Certificate[certs.size()];
+ certs.toArray(x509Chain);
+ return x509Chain;
+ } else {
+ return null;
+ }
+ }
+
+
+ public static void main(String[] args) throws Exception {
+ if (args.length < 2) {
+ System.out.println("KeyStoreBuilder: creates '[alias].jks' (Java Key Store)");
+ System.out.println(" -topk8 mode: creates '[alias].pem' (x509 chain + unencrypted pkcs8)");
+ System.out.println("[alias] will be set to the first CN value of the X509 certificate.");
+ System.out.println("-------------------------------------------------------------------");
+ System.out.println("Usage1: [password] [file:pkcs12]");
+ System.out.println("Usage2: [password] [file:private-key] [file:certificate-chain]");
+ System.out.println("Usage3: -topk8 [password] [file:jks]");
+ System.out.println("-------------------------------------------------------------------");
+ System.out.println("[private-key] can be openssl format, or pkcs8.");
+ System.out.println("[password] decrypts [private-key], and also encrypts outputted JKS file.");
+ System.out.println("All files can be PEM or DER.");
+ System.exit(1);
+ }
+ char[] password = args[0].toCharArray();
+ boolean toPKCS8 = false;
+ if ("-topk8".equalsIgnoreCase(args[0])) {
+ toPKCS8 = true;
+ password = args[1].toCharArray();
+ args[1] = args[2];
+ args[2] = null;
+ }
+
+ FileInputStream fin1 = new FileInputStream(args[1]);
+ byte[] bytes1 = Util.streamToBytes(fin1);
+ byte[] bytes2 = null;
+ if (args.length > 2 && args[2] != null) {
+ FileInputStream fin2 = new FileInputStream(args[2]);
+ bytes2 = Util.streamToBytes(fin2);
+ }
+
+ KeyStore ks = build(bytes1, bytes2, password);
+ Enumeration en = ks.aliases();
+ String alias = "keystorebuilder";
+
+ // We're going to assume that the biggest key is the one we want
+ // to convert to PKCS8 (PEM). That's until someone figures out a
+ // better way to deal with this annoying situation (more than 1
+ // key in the KeyStore).
+ int biggestKey = 0;
+ while (en.hasMoreElements()) {
+ String s = (String) en.nextElement();
+ try {
+ PrivateKey pk = (PrivateKey) ks.getKey(s, password);
+ byte[] encoded = pk.getEncoded();
+ int len = encoded != null ? encoded.length : 0;
+ if (len >= biggestKey) {
+ biggestKey = len;
+ alias = s;
+ }
+ } catch (Exception e) {
+ // oh well, try next one.
+ System.err.println(e);
+ }
+ }
+
+ String suffix = toPKCS8 ? ".pem" : ".jks";
+ String fileName = alias;
+ Certificate[] chain = ks.getCertificateChain(alias);
+ if (chain != null && chain[0] != null) {
+ String cn = Certificates.getCN((X509Certificate) chain[0]);
+ cn = cn != null ? cn.trim() : "";
+ if (!"".equals(cn)) {
+ fileName = cn;
+ }
+ }
+
+ File f = new File(fileName + suffix);
+ int count = 1;
+ while (f.exists()) {
+ f = new File(alias + "_" + count + suffix);
+ count++;
+ }
+
+ FileOutputStream fout = new FileOutputStream(f);
+ if (toPKCS8) {
+ List pemItems = new LinkedList();
+ PrivateKey key = (PrivateKey) ks.getKey(alias, password);
+ chain = ks.getCertificateChain(alias);
+ byte[] pkcs8DerBytes = null;
+ if (key instanceof RSAPrivateCrtKey) {
+ RSAPrivateCrtKey rsa = (RSAPrivateCrtKey) key;
+ Asn1Sequence seq = new Asn1Sequence();
+ seq.addItem(new Asn1Integer(BigInteger.ZERO));
+ seq.addItem(new Asn1Integer(rsa.getModulus()));
+ seq.addItem(new Asn1Integer(rsa.getPublicExponent()));
+ seq.addItem(new Asn1Integer(rsa.getPrivateExponent()));
+ seq.addItem(new Asn1Integer(rsa.getPrimeP()));
+ seq.addItem(new Asn1Integer(rsa.getPrimeQ()));
+ seq.addItem(new Asn1Integer(rsa.getPrimeExponentP()));
+ seq.addItem(new Asn1Integer(rsa.getPrimeExponentQ()));
+ seq.addItem(new Asn1Integer(rsa.getCrtCoefficient()));
+ byte[] derBytes = seq.encode();
+ PKCS8Key pkcs8 = new PKCS8Key(derBytes, null);
+ pkcs8DerBytes = pkcs8.getDecryptedBytes();
+ } else if (key instanceof DSAPrivateKey) {
+ DSAPrivateKey dsa = (DSAPrivateKey) key;
+ DSAParams params = dsa.getParams();
+ BigInteger g = params.getG();
+ BigInteger p = params.getP();
+ BigInteger q = params.getQ();
+ BigInteger x = dsa.getX();
+ BigInteger y = q.modPow(x, p);
+
+ Asn1Sequence seq = new Asn1Sequence();
+ seq.addItem(new Asn1Integer(BigInteger.ZERO));
+ seq.addItem(new Asn1Integer(p));
+ seq.addItem(new Asn1Integer(q));
+ seq.addItem(new Asn1Integer(g));
+ seq.addItem(new Asn1Integer(y));
+ seq.addItem(new Asn1Integer(x));
+ byte[] derBytes = seq.encode();
+ PKCS8Key pkcs8 = new PKCS8Key(derBytes, null);
+ pkcs8DerBytes = pkcs8.getDecryptedBytes();
+ }
+ if (chain != null && chain.length > 0) {
+ for (int i = 0; i < chain.length; i++) {
+ X509Certificate x509 = (X509Certificate) chain[i];
+ byte[] derBytes = x509.getEncoded();
+ PEMItem item = new PEMItem(derBytes, "CERTIFICATE");
+ pemItems.add(item);
+ }
+ }
+ if (pkcs8DerBytes != null) {
+ PEMItem item = new PEMItem(pkcs8DerBytes, "PRIVATE KEY");
+ pemItems.add(item);
+ }
+ byte[] pem = PEMUtil.encode(pemItems);
+ fout.write(pem);
+ } else {
+ // If we're not converting to unencrypted PKCS8 style PEM,
+ // then we are converting to Sun JKS. It happens right here:
+ KeyStore jks = KeyStore.getInstance(KeyStore.getDefaultType());
+ jks.load(null, password);
+ jks.setKeyEntry(alias, ks.getKey(alias, password), password, ks.getCertificateChain(alias));
+ jks.store(fout, password);
+ }
+ fout.flush();
+ fout.close();
+ System.out.println("Successfuly wrote: [" + f.getPath() + "]");
+ }
+
+
+}
http://git-wip-us.apache.org/repos/asf/directory-kerby/blob/a2c604ee/kerby-pkix/src/main/java/org/apache/commons/ssl/LDAPSocket.java
----------------------------------------------------------------------
diff --git a/kerby-pkix/src/main/java/org/apache/commons/ssl/LDAPSocket.java b/kerby-pkix/src/main/java/org/apache/commons/ssl/LDAPSocket.java
new file mode 100644
index 0000000..8c6dbcd
--- /dev/null
+++ b/kerby-pkix/src/main/java/org/apache/commons/ssl/LDAPSocket.java
@@ -0,0 +1,80 @@
+/*
+ * $HeadURL: http://juliusdavies.ca/svn/not-yet-commons-ssl/tags/commons-ssl-0.3.16/src/java/org/apache/commons/ssl/LDAPSocket.java $
+ * $Revision: 165 $
+ * $Date: 2014-04-24 16:48:09 -0700 (Thu, 24 Apr 2014) $
+ *
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+
+package org.apache.commons.ssl;
+
+import javax.net.SocketFactory;
+import java.io.IOException;
+import java.security.GeneralSecurityException;
+
+/**
+ * @author Credit Union Central of British Columbia
+ * @author <a href="http://www.cucbc.com/">www.cucbc.com</a>
+ * @author <a href="mailto:juliusdavies@cucbc.com">juliusdavies@cucbc.com</a>
+ * @since 28-Feb-2006
+ */
+public final class LDAPSocket extends SSLClient {
+ private static final LDAPSocket INSTANCE;
+
+ static {
+ LDAPSocket sf = null;
+ try {
+ sf = new LDAPSocket();
+ } catch (Exception e) {
+ System.out.println("could not create LDAPSocket: " + e);
+ e.printStackTrace();
+ } finally {
+ INSTANCE = sf;
+ }
+ }
+
+ private LDAPSocket() throws GeneralSecurityException, IOException {
+ super();
+
+ // For now we setup the usual trust infrastructure, but consumers
+ // are encouraged to call getInstance().addTrustMaterial() or
+ // getInstance().setTrustMaterial() to customize the trust.
+ if (TrustMaterial.JSSE_CACERTS != null) {
+ setTrustMaterial(TrustMaterial.JSSE_CACERTS);
+ } else {
+ setTrustMaterial(TrustMaterial.CACERTS);
+ }
+ }
+
+ public static SocketFactory getDefault() {
+ return getInstance();
+ }
+
+ public static LDAPSocket getInstance() {
+ return INSTANCE;
+ }
+
+}