初始化SSLContext失败

时间:2014-07-07 06:54:18

标签: java ssl ssl-certificate

当我尝试使用getServerSocket方法初始化SSLServerSocket时,如下所示,定义了密钥库:

public static ServerSocket getServerSocket(int port) {
    System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true");
    ServerSocket serverSocket = null;
    secureRandom = new SecureRandom();
    Thread.currentThread().sleep(30000);
    secureRandom.nextInt();

    setupClientKeyStore();
    setupServerKeystore();
    setupSSLContext();

    SSLServerSocketFactory sf = sslContext.getServerSocketFactory();
    serverSocket = sf.createServerSocket(port);
    ((SSLServerSocket)serverSocket).setNeedClientAuth(true);
    }
    return serverSocket;
}

private static void setupClientKeyStore() throws GeneralSecurityException, IOException   {
    clientKeyStore = KeyStore.getInstance("JKS");

    KeyStore client = KeyStore.getInstance("JKS");
    client.load( new FileInputStream("client.public"), "public".toCharArray() );

    KeyStore client1 = KeyStore.getInstance( "JKS" );
    client1.load( new FileInputStream("client1.public"), "public".toCharArray() );

    KeyStore.Entry clientpublic = client.getEntry("clientpublic", null);
    KeyStore.Entry client1public = client1.getEntry("client1public", null);

    clientKeyStore.load(null, null);
    clientKeyStore.setEntry("clientpublic", clientpublic, null);
    clientKeyStore.setEntry("client1public", client1public, null);

}

private static void setupServerKeystore() throws GeneralSecurityException, IOException       {
    serverKeyStore = KeyStore.getInstance( "JKS" );
    serverKeyStore.load( new FileInputStream( "server.private" ),
            passphrase.toCharArray() );
}

private static void setupSSLContext() throws GeneralSecurityException, IOException {
    TrustManagerFactory tmf = TrustManagerFactory.getInstance( "SunX509" );
    tmf.init( clientKeyStore );

    KeyManagerFactory kmf = KeyManagerFactory.getInstance( "SunX509" );
    kmf.init( serverKeyStore, passphrase.toCharArray() );

    sslContext = SSLContext.getInstance("TLS");
    sslContext.init( kmf.getKeyManagers(),
            tmf.getTrustManagers(),
            secureRandom);
}

它抛出异常:

trigger seeding of SecureRandom
trigger seeding of SecureRandom
done seeding SecureRandom
done seeding SecureRandom
java.lang.IllegalStateException: SSLContext is not initialized 
atcom.sun.net.ssl.internal.ssl.SSLContextImpl.enginegetServerSocketFactory<SSLContextImpl.java.153>
at javax.net.ssl.SSLContext.getServerSocketFactory<SSLContext.java.272>

Allow unsafe renegotiation: false
Allow legacy hello message: true
Is initial handshake: true
Is secure renegotiation: false

我无法理解为什么它会将“触发播种SecureRandom”和“完成播种SecureRandom”两次。

1 个答案:

答案 0 :(得分:0)

显然输出出现了两次,因为你同时在两个线程中运行这个代码。我建议你在两个线程中也使用相同的Runnable,这可以完全解释这个失败。

在nextInt()之前你不需要睡眠。我不明白你为什么要将KeyStore条目设置为null。