2014-07-07 255 views
-2

當我嘗試初始化getServerSocket方法SSLServerSocket與定義密鑰庫如下所示:失敗初始化的SSLContext

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「兩次。

+2

您需要提供有關您正在使用的代碼的更多詳細信息,而不僅僅是這一行。這可能不是正確的,因爲'init'不是'SSLContext'的靜態方法。 – Bruno

+0

抱歉,它會從SSLContext類的實例中調用init方法。 – user3104352

+0

這是什麼代碼? – Bruno

回答

0

顯然,輸出顯示兩次,因爲您在兩個線程中同時運行此代碼。我建議你在兩個線程中也使用相同的Runnable,這將完全解釋這個失敗。

在nextInt()之前,您不需要睡眠。我不明白你爲什麼要將KeyStore條目設置爲null。