Java:通过资源加载SSL密钥库

时间:2010-07-14 15:29:35

标签: java ssl ssl-certificate keystore

如果我有:

System.setProperty("javax.net.ssl.keyStore", '/etc/certificates/fdms/WS1001237590._.1.ks');
System.setProperty("javax.net.ssl.keyStorePassword", 'DV8u4xRVDq');
System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true");

我可以毫无问题地打开安全连接。

但是,我想将证书直接存储在战争中,所以我使用:(文件输入流最终将成为资源流,但我这样做是为了让它工作。)

System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true");
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream("/etc/certificates/fdms/WS1001237590._.1.ks"), "DV8u4xRVDq".toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, "DV8u4xRVDq".toCharArray());
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(kmf.getKeyManagers(), null, null);

现在,如果我打开相同的连接,我会得到:javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure

5 个答案:

答案 0 :(得分:9)

我不得不做一些类似的事情。我有一个证书文件,我不得不想办法加载它并用它来进行SSL连接。希望我所做的将帮助你。

首先,我必须创建一个信任管理器:

public class MyX509TrustManager implements X509TrustManager {

    X509TrustManager pkixTrustManager;

    MyX509TrustManager() throws Exception {

        String certFile = "/certificates/MyCertFile.cer";

        Certificate myCert = CertificateFactory.getInstance("X509").generateCertificate(this.getClass().getResourceAsStream(valicertFile));

        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(null, "".toCharArray());
        keyStore.setCertificateEntry("myCert", myCert);

        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("PKIX");
        trustManagerFactory.init(keyStore);

        TrustManager trustManagers[] = trustManagerFactory.getTrustManagers();

        for(TrustManager trustManager : trustManagers) {
            if(trustManager instanceof X509TrustManager) {
                pkixTrustManager = (X509TrustManager) trustManager;
                return;
            }
        }

        throw new Exception("Couldn't initialize");
    }

    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        pkixTrustManager.checkServerTrusted(chain, authType);
    }

    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        pkixTrustManager.checkServerTrusted(chain, authType);
    }

    public X509Certificate[] getAcceptedIssuers() {
        return pkixTrustManager.getAcceptedIssuers();
    }
}

之后我不得不创建一个使用我的信任管理器的套接字工厂:

public class MySSLProtocolSocketFactory implements SecureProtocolSocketFactory {

    private SSLContext sslContext = null;

    public MySSLProtocolSocketFactory() {
        super();
    }

    private static SSLContext createMySSLContext() {
        try {
            MyX509TrustManager myX509TrustManager = new MyX509TrustManager();
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, new MyX509TrustManager[] { myX509TrustManager}, null);
            return context;
        }

        catch(Exception e) {
            Log.error(Log.Context.Net, e);
            return null;
        }
    }

    private SSLContext getSSLContext() {
        if(this.sslContext == null) {
            this.sslContext = createMySSLContext();
        }

        return this.sslContext;
    }

    public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort) throws IOException {
        return getSSLContext().getSocketFactory().createSocket(host, port, clientHost, clientPort);
    }

    public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params) throws IOException {
        if(params == null) {
            throw new IllegalArgumentException("Parameters may not be null");
        }

        int timeout = params.getConnectionTimeout();
        SocketFactory socketFactory = getSSLContext().getSocketFactory();

        if(timeout == 0) {
            return socketFactory.createSocket(host, port, localAddress, localPort);
        }

        else {
            Socket socket = socketFactory.createSocket();
            SocketAddress localAddr = new InetSocketAddress(localAddress, localPort);
            SocketAddress remoteAddr = new InetSocketAddress(host, port);
            socket.bind(localAddr);
            socket.connect(remoteAddr, timeout);
            return socket;
        }
    }

    public Socket createSocket(String host, int port) throws IOException {
        return getSSLContext().getSocketFactory().createSocket(host, port);
    }

    public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException {
        return getSSLContext().getSocketFactory().createSocket(socket, host, port, autoClose);
    }

    public boolean equals(Object obj) {
        return ((obj != null) && obj.getClass().equals(MySSLProtocolSocketFactory.class));
    }

    public int hashCode() {
        return MySSLProtocolSocketFactory.class.hashCode();
    }
}

然后我用那个套接字工厂发送我的POST:

Protocol.registerProtocol("myhttps", new Protocol("myhttps", new MySSLProtocolSocketFactory(), 443));

PostMethod postMethod = new PostMethod("myhttps://some.url.here");

HttpClient client = new HttpClient();
int status = client.executeMethod(postMethod);

我唯一想知道的是如何简单地将证书文件添加到常规密钥库。我在研究过程中发现的所有示例源代码都指向创建套接字因子,然后在该套接字工厂中注册协议。也许有一种方法可以简单地使用套接字工厂来建立连接而无需注册协议;我没有彻底调查过。在我的特殊情况下,创建一个特定的协议是必要的。希望这将使您的进一步发展。我承认它似乎有点迂回;我最初做的时候也有同感。但这是我开始工作的唯一方式。也许其他人有更好的解决方案。

答案 1 :(得分:4)

为了后人的缘故,所有这些都太复杂了,我们几乎只是检查了静态块:

if( environment == 'production') {
    System.setProperty("javax.net.ssl.keyStore",                    '/etc/certificates/prod/keystore.ks');
    System.setProperty("javax.net.ssl.keyStorePassword",            'password');
    System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true");
} else {
    System.setProperty("javax.net.ssl.keyStore",                    '/etc/certificates/test/keystore.ks');
    System.setProperty("javax.net.ssl.keyStorePassword",            'password');
    System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true");
}

答案 2 :(得分:3)

使用Axis,我认为您需要通过以下方式配置SSLSocketFactory

AxisProperties.setProperty("axis.socketSecureFactory",
    "com.example.MySSLSocketFactory");

其中com.example.MySSLSocketFactory是您实施org.apache.axis.components.net.SecureSocketFactory的类(您可以扩展org.apache.axis.components.net.JSSESocketFactory)。

create方法中,使用从您配置的SSLContext获取的套接字工厂创建套接字。

答案 3 :(得分:2)

如果需要,这里有一个API可以轻松创建SSLSocket和SSLServerSocket:

https://github.com/gpotter2/SSLKeystoreFactories

它不需要任何其他罐....只需获取文件并使用它们:

SSLSocket s = SSLSocketKeystoreFactory.getSocketWithCert(ip, port, 
   Main.class.getResourceAsStream("/mykey.jks"), "password")

或者:

SSLServerSocket s = SSLServerSocketKeystoreFactory.getSocketWithCert(port, 
   Main.class.getResourceAsStream("/mykey.jks"), "password")

这更容易使用:)

答案 4 :(得分:0)

我有类似的问题,我解决了创建一个使用来自和输入流的密钥库返回SSL上下文的函数的问题。

   protected SSLContext getSslCtx(InputStream is, String password) {
    try {
        // Load keystore
        KeyStore keystore = KeyStore.getInstance("JKS");
        keystore.load(is, password.toCharArray());

        // Load trust manager
        TrustManagerFactory trustMgrFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustMgrFactory.init(keystore);

        // Load key manager
        KeyManagerFactory keyMgrFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyMgrFactory.init(keystore, password.toCharArray());

        // Create SSL context
        SSLContext ctx = SSLContext.getInstance("TLSv1.2");
        ctx.init(keyMgrFactory.getKeyManagers(), trustMgrFactory.getTrustManagers(), null);
        return ctx;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

希望这会有所帮助。