2012-02-09 93 views
-2

我需要在一个套接字中使用ssl连接进行密钥对,而不会在客户端中进行任何更改。在一个SSL套接字连接中使用两个私钥(keystore)和两个公钥(truststore)

为什么?

因为一个客户端在信任存储中使用CN属性进行连接握手,而其他客户端使用同一属性中的另一个值以相同的方式处理相同的任务。

所以我需要使用两个关键的商店(私人)具有独特的属性,CN和也别名和份额两种不同的信任存储(公钥)具有独特的CN属性也是别名也。

描述波纹管:

keyStore1

密钥库类型:JKS

密钥库提供:SUN

别名:对identity1

拥有者:CN = APP1 ...

发行人:CN = APP1 ...

trustStore1

别名:对identity1

业主:CN = APP1 ...

发行机构:CN = app1 ...

keyStore2

别名:identity2

业主:CN = APP 2 ...

发行人:CN = APP 2 ...

trustStore2

别名:identity2

业主:CN = APP 2 ...

发行人:CN = APP 2 ...

我试图实现这种方式这个功能:

KeyStore KeyStore1; 

       try { 
        String keyStoreFile1 = "privatekey1"; 
        String keyStoreType1 = "jks"; 
        char[] keyStorePwd1 = "password".toCharArray(); 

        keyStore1 = KeyStore.getInstance(keyStoreType1); 
        keyStore1.load(new FileInputStream(keyStoreFile1), keyStorePwd1); 
       } catch (java.security.GeneralSecurityException thr) { 
        throw new IOException("Cannot load keystore (" + thr + ")"); 
       } 

       KeyStore trustStore1; 

       try { 
        String trustStoreFile1 = "publickey1"; 
        String trustStoreType1 = "jks"; 
        char[] trustStorePwd1 = "password".toCharArray(); 

        trustStore1 = KeyStore.getInstance(trustStoreType1); 
        trustStore.load(new FileInputStream(trustStoreFile1), trustStorePwd1); 
       } catch (java.security.GeneralSecurityException thr) { 
        throw new IOException("Cannot load truststore (" + thr + ")"); 
       } 


       KeyStore keyStore2; 

       try { 
        String keyStoreFile2 = "privatekey2"; 
        String keyStoreType2 = "jks"; 
        char[] keyStorePwd2 = "anotherpass".toCharArray(); 

        keyStore2 = KeyStore.getInstance(key2StoreType); 
        keyStore2.load(new FileInputStream(keyStoreFile2), keyStorePwd2); 
       } catch (java.security.GeneralSecurityException thr) { 
        throw new IOException("Cannot load keystore (" + thr + ")"); 
       } 

       KeyStore trustStore2; 

       try { 
        String trustStoreFile2 = "publickey2"; 
        String trustStoreType2 = "jks"; 
        char[] trustStorePwd2 = "anotherpass".toCharArray(); 

        trustStore2 = KeyStore.getInstance(trustStoreType2); 
        trustStore2.load(new FileInputStream(trustStoreFile2), trustStorePwd2); 
       } catch (java.security.GeneralSecurityException thr) { 
        throw new IOException("Cannot load truststore (" + thr + ")"); 
       } 



       KeyManagerFactory kmfkey1 = KeyManagerFactory 
.getInstance(KeyManagerFactory.getkey1Algorithm()); 

       kmfkey1.init(keyStore1, "password".toCharArray()); 

       TrustManagerFactory tmfkey1 = 
         TrustManagerFactory.getInstance(TrustManagerFactory.getkey1Algorithm()); 
       tmfkey1.init(trustStore1); 


       SSLContext ctx = SSLContext.getInstance("SSL"); 
       ctx.init(kmfkey1.getKeyManagers(), tmfkey1.getTrustManagers(), null); 


       KeyManagerFactory kmfkey2 = KeyManagerFactory. 
getInstance(KeyManagerFactory.getkey1Algorithm()); 

       kmfkey2.init(keyStore2, "password".toCharArray()); 

       TrustManagerFactory tmfkey2 = TrustManagerFactory 
.getInstance(TrustManagerFactory.getkey1Algorithm()); 

       tmfkey2.init(trustStore2); 


       SSLContext ctxkey2 = SSLContext.getInstance("SSL"); 
       ctxkey2.init(kmfkey2.getKeyManagers(), tmfkey2.getTrustManagers(), null); 

       SSLServerSocketFactory sslSrvSockFact = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); 

       serverSocket = sslSrvSockFact.createServerSocket(port); 

... 但我收到此错误信息

...

java.security.KeyStoreException:在com.sun.net未初始化密钥库中 在java.security.KeyStore.aliases(KeyStore.java:941) .ssl.internal.ssl.SunX509KeyManagerImpl。(SunX509KeyManagerImpl.java:106) at com.sun.net.ssl.internal.ssl.KeyManagerFactoryImpl $ SunX509.engineInit(KeyManagerFactoryImpl.java:41) at javax.net.ssl。 KeyManagerFactory.init(KeyManagerFactory.java:192)

...

所以我真的很想知道是否有可能在一个套接字连接中使用密钥对,或以不能看到或处理的不同方式解决此问题。

编辑1

布鲁诺,你能不能给我一个完整的或完整的例子吗?

因为目前尚不清楚我....

我想两件事情:

One解决方案就是把两个键下面先前建议的私人密钥库里面...但不工作我接收波纹管的消息:在螺纹

异常 “主” java.lang.NoSuchMethodError:javax.net.ssl.SSLContext.setDefault(Ljavax /净/ SSL /的SSLContext) 在... initialiseManager( 499)

你是对的...我还需要选择其中一个方面或

javax.net.ssl.SSLException: 无证书或密钥对应于启用的SSL密码套件。 而试图将消息发送到服务器...

其次,我跟着你的建议......但是SSL Socket连接不启动

我实现了这个与许多其他人是边打边 帮助代码在这里本网站...感谢所有

private KeyManager[] getKeyManagers() throws IOException, GeneralSecurityException { 

     // First, get the default KeyManagerFactory. 
     String alg = KeyManagerFactory.getDefaultAlgorithm(); 
     KeyManagerFactory kmFact = KeyManagerFactory.getInstance(alg); 

     // Next, set up the KeyStore to use. We need to load the file into 
     // a KeyStore instance. 

     File keyFile = new File("privatekey1"); 

     FileInputStream fis = new FileInputStream(keyFile); 
     LogManager.log("Loaded keystore privatekey1 " + keyFile.getAbsolutePath(), 
LogManager.LOG_LOWEST_LEVEL); 
     KeyStore ks = KeyStore.getInstance("jks"); 
     String keyStorePassword = "password"; 
     ks.load(fis, keyStorePassword.toCharArray()); 
     fis.close(); 
     // Now we initialise the KeyManagerFactory with this KeyStore 
     kmFact.init(ks, keyStorePassword.toCharArray()); 


     KeyManagerFactory dkmFact = KeyManagerFactory.getInstance(alg); 

     File keyFileTwo = new File("privatekey2"); 

     FileInputStream fisTwo = new FileInputStream(keyFileTwo); 
     LogManager.log("Loaded keystore privatekey2 " + keyFileTwo.getAbsolutePath(), LogManager.LOG_LOWEST_LEVEL); 
     KeyStore ksTwo = KeyStore.getInstance("jks"); 
     String keyStorePasswordTwo = "password"; 
     ksTwo.load(fisTwo, keyStorePasswordTwo.toCharArray()); 
     fisTwo.close(); 
     // Now we initialise the KeyManagerFactory with this KeyStore 
     dkmFact.init(ksTwo, keyStorePasswordTwo.toCharArray()); 


     // default 
     //KeyManagerFactory dkmFact = KeyManagerFactory.getInstance(alg); 
     //dkmFact.init(null, null); 


     // Get the first X509KeyManager in the list 
     X509KeyManager customX509KeyManager = getX509KeyManager(alg, kmFact); 
     X509KeyManager jvmX509KeyManager = getX509KeyManager(alg, dkmFact); 

     KeyManager[] km = {new MultiKeyStoreManager(jvmX509KeyManager, customX509KeyManager)}; 
     LogManager.log("Number of key managers registered:" + km.length, LogManager.LOG_LOWEST_LEVEL); 
     return km; 
    } 

    /** 
    * Find a X509 Key Manager compatible with a particular algorithm 
    * @param algorithm 
    * @param kmFact 
    * @return 
    * @throws NoSuchAlgorithmException 
    */ 
    private X509KeyManager getX509KeyManager(String algorithm, KeyManagerFactory kmFact) 
      throws NoSuchAlgorithmException { 
     KeyManager[] keyManagers = kmFact.getKeyManagers(); 

     if (keyManagers == null || keyManagers.length == 0) { 
      throw new NoSuchAlgorithmException("The default algorithm :" + algorithm + " produced no key managers"); 
     } 

     X509KeyManager x509KeyManager = null; 

     for (int i = 0; i < keyManagers.length; i++) { 
      if (keyManagers[i] instanceof X509KeyManager) { 
       x509KeyManager = (X509KeyManager) keyManagers[i]; 
       break; 
      } 
     } 

     if (x509KeyManager == null) { 
      throw new NoSuchAlgorithmException("The default algorithm :" + algorithm + " did not produce a X509 Key manager"); 
     } 
     return x509KeyManager; 
    } 

    private void initialiseManager(int iPort) throws IOException, GeneralSecurityException { 
     // Next construct and initialise a SSLContext with the KeyStore and 
     // the TrustStore. We use the default SecureRandom. 

     // load your key store as a stream and initialize a KeyStore 
     File trustFile = new File("publicKey"); 
     LogManager.log("Trust File Loaded " + trustFile.getAbsolutePath(), LogManager.LOG_LOWEST_LEVEL); 

     InputStream trustStream = new FileInputStream(trustFile); 
     KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); 

     // if your store is password protected then declare it (it can be null however) 
     char[] trustPassword = "password".toCharArray(); 

     // load the stream to your store 
     trustStore.load(trustStream, trustPassword); 

     File trustFileTwo = new File("publicKeyTwo"); 
     LogManager.log("Trust File Loaded " + trustFileTwo.getAbsolutePath(), LogManager.LOG_LOWEST_LEVEL); 

     InputStream trustStreamTwo = new FileInputStream(trustFileTwo); 
     KeyStore trustStoreTwo = KeyStore.getInstance(KeyStore.getDefaultType()); 

     // if your store is password protected then declare it (it can be null however) 
     char[] trustPasswordTwo = "password".toCharArray(); 

     // load the stream to your store 
     trustStoreTwo.load(trustStreamTwo, trustPasswordTwo); 


     // initialize a trust manager factory with the trusted store 
     TrustManagerFactory trustFactory = 
       TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); 
     trustFactory.init(trustStore); 
     trustFactory.init(trustStoreTwo); 

     // get the trust managers from the factory 
     TrustManager[] managers = trustFactory.getTrustManagers(); 


     SSLContext context = SSLContext.getInstance("SSL"); 
     context.init(getKeyManagers(), managers, new SecureRandom()); 
     SSLContext.setDefault(context); 

     SSLServerSocketFactory sslSrvFact = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); 

     serverSocket = sslSrvFact.createServerSocket(iPort); 
     // this method didn't create a Socket Connection correctly 

    } 

    class MultiKeyStoreManager implements X509KeyManager { 

     private final X509KeyManager jvmKeyManager; 
     private final X509KeyManager customKeyManager; 

     public MultiKeyStoreManager(X509KeyManager jvmKeyManager, X509KeyManager customKeyManager) { 
      this.jvmKeyManager = jvmKeyManager; 
      this.customKeyManager = customKeyManager; 
     } 

     @Override 
     public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) { 
      // try the first key manager 
      String alias = customKeyManager.chooseClientAlias(keyType, issuers, socket); 
      if (alias == null) { 
       alias = jvmKeyManager.chooseClientAlias(keyType, issuers, socket); 
       LogManager.log("Reverting to JVM CLIENT alias : " + alias, LogManager.LOG_LOWEST_LEVEL); 
      } 

      return alias; 

     } 

     @Override 
     public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) { 
      // try the first key manager 
      String alias = customKeyManager.chooseServerAlias(keyType, issuers, socket); 
      if (alias == null) { 
       alias = jvmKeyManager.chooseServerAlias(keyType, issuers, socket); 
       LogManager.log("Reverting to JVM Server alias : " + alias ,LogManager.LOG_LOWEST_LEVEL); 
      } 
      return alias; 
     } 

     @Override 
     public String[] getClientAliases(String keyType, Principal[] issuers) { 
      String[] cAliases = customKeyManager.getClientAliases(keyType, issuers); 
      String[] jAliases = jvmKeyManager.getClientAliases(keyType, issuers); 
      LogManager.log("Supported Client Aliases Custom: " + cAliases.length + " JVM : " + jAliases.length, 
        LogManager.LOG_LOWEST_LEVEL); 
      return (String[]) ArrayUtils.addAll(cAliases, jAliases); 
     } 

     @Override 
     public PrivateKey getPrivateKey(String alias) { 
      PrivateKey key = customKeyManager.getPrivateKey(alias); 
      if (key == null) { 
       System.out.println("Reverting to JVM Key : " + alias); 
       return jvmKeyManager.getPrivateKey(alias); 
      } else { 
       return key; 
      } 
     } 

     @Override 
     public String[] getServerAliases(String keyType, Principal[] issuers) { 
      String[] cAliases = customKeyManager.getServerAliases(keyType, issuers); 
      String[] jAliases = jvmKeyManager.getServerAliases(keyType, issuers); 
      LogManager.log("Supported Server Aliases Custom: " + cAliases.length + " JVM : " + jAliases.length, 
        LogManager.LOG_LOWEST_LEVEL); 
      return (String[]) ArrayUtils.addAll(cAliases, jAliases); 
     } 

     @Override 
     public java.security.cert.X509Certificate[] getCertificateChain(String string) { 
      java.security.cert.X509Certificate[] chain = customKeyManager.getCertificateChain("alias_key1"); 
      if (chain == null || chain.length == 0) { 
       LogManager.log("Reverting to JVM Chain : " + string, LogManager.LOG_LOWEST_LEVEL); 
       return jvmKeyManager.getCertificateChain("alias_key2"); 
      } else { 
       return chain; 
      } 
     } 
    } 

and this gave me this status 

* 2012.02.09 18时47分00秒激活SSL连接

2012.02.09 18时47分00秒[... ::运行]

2012.02.09十八时47分00秒信托文件中加载公钥

2012.02.09十八时47分00秒信托文件加载publicKeyTwo

2012.02.09十八时47分00秒加载密钥库专用密钥专用密钥

2012.02.09 18:47:00加载密钥库privateKey2 privateKeyTwo

2012.02。09十八点47分00秒的关键管理人员的注册数:1 *

却没有任何反应,当我试图发送邮件服务器...

正在很难找到真正工作在这样的一个例子案件。

EDIT 2

嗨布鲁诺

关于这个问题,Java和SSH,我真的你先进的知识非常感谢您 帮助。所有这些信息都可以帮助我更好地理解这个问题,同时为我显示的方式... Thx很多

而且你是对的...我在Java 5上使用Java 6的代码JRE

但再次下你的食谱,我得到这个代码:

  // Load the key store: change store type if needed 
     KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); 
     FileInputStream fis = new FileInputStream("keyStore1"); 
     char[] keyPass = "passw".toCharArray(); 
     try { 
      ks.load(fis, keyPass); 
     } finally { 
      if (fis != null) { 
       fis.close(); 
      } 
     } 

     // Get the default Key Manager 
     KeyManagerFactory kmf = KeyManagerFactory.getInstance(
       KeyManagerFactory.getDefaultAlgorithm()); 
     kmf.init(ks, keyPass); 

     final X509KeyManager origKm = (X509KeyManager) kmf.getKeyManagers()[0]; 
     X509KeyManager km = new X509KeyManager() { 

      public String chooseServerAlias(String[] keyType, Principal[] issuers, Socket socket) { 
       String alias; 

       InetAddress remoteAddress = socket.getInetAddress(); 

       if (remoteAddress.getHostAddress().equalsIgnoreCase("11.111.111.11")) { 
        alias = "alias1"; 
        LogManager.log("Reverting to JVM CLIENT alias : " + alias, LogManager.LOG_LOWEST_LEVEL); 
       } else { 
        alias = "alias2"; 
        LogManager.log("Reverting to JVM CLIENT alias : " + alias, LogManager.LOG_LOWEST_LEVEL); 
       } 
       return alias; 
      } 

      public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) { 
       // try this key manager 
       String alias = origKm.chooseClientAlias(keyType, issuers, socket); 
       LogManager.log("Reverting to JVM CLIENT alias : " + alias, LogManager.LOG_LOWEST_LEVEL); 
       return alias; 
      } 

      public String[] getClientAliases(String keyType, Principal[] issues) { 

       String[] cAliases = origKm.getClientAliases(keyType, issues); 
       LogManager.log("Supported Client Aliases : " + cAliases.length, LogManager.LOG_LOWEST_LEVEL); 
       return cAliases; 

      } 

      public String[] getServerAliases(String keyType, Principal[] issues) { 

       String[] sAliases = origKm.getServerAliases(keyType, issues); 
       LogManager.log("Supported Server Aliases: " + sAliases.length, LogManager.LOG_LOWEST_LEVEL); 
       return sAliases; 

      } 

      public String chooseServerAlias(String keyType, Principal[] issues, Socket socket) { 

       // try this key manager 
       String alias = origKm.chooseServerAlias(keyType, issues, socket); 
       LogManager.log("Reverting to JVM Server alias : " + alias, LogManager.LOG_LOWEST_LEVEL); 
       return alias; 
      } 

      public X509Certificate[] getCertificateChain(String keyType) { 

       // here I could specify my other keystore, keystore2 how I could do this? 

       // I'm thinking in the righ way when I implemented this code to get the correct private key? 

       X509Certificate[] chain = origKm.getCertificateChain("alias1"); 
       if (chain == null || chain.length == 0) { 
        LogManager.log("Reverting to JVM Chain : " + keyType, LogManager.LOG_LOWEST_LEVEL); 

        return origKm.getCertificateChain("alias2"); 
       } else { 
        return chain; 
       } 
      } 

      public PrivateKey getPrivateKey(String alias) { 

       PrivateKey key = origKm.getPrivateKey(alias); 

       // here I could get my other keystore according the alias, for example 
       // keystore2 how I could do this? 

       LogManager.log("Reverting to JVM Key : " + alias, LogManager.LOG_LOWEST_LEVEL); 
       return key; 
      } 
     }; 

     SSLContext sslContext = SSLContext.getInstance("SSL"); 
     sslContext.init(new KeyManager[]{km}, null, null); 

     SSLServerSocketFactory sslSrvFact = sslContext.getServerSocketFactory(); 
     objServerSocket = sslSrvFact.createServerSocket(iPort); 

是正是这一点我需要实现我的目标是什么?

编辑3

使用这种方法得到了一个客户端和服务器之间的握手使用第二 密钥库与别名2利用公众的信任,商店2客户端

...但我还是当我的错误试图用信托商店1在客户端

...收到一则由[地址=/11.111.111.11] 恢复到JVM服务器别名:别名2 恢复到JVM密钥:别名2 错误retriving: javax.net.ssl.SSLHandshakeException:收到致命警报:certificate_unknown

我的代码不会改变使用与alias1私人key1的服务器......当客户端使用带有证书alias1公众truststore1 ...

更何况是必要的解决这个做......我认为这是最终的解决方案...附近再次

THX!

EDIT 4

布鲁诺,我按照你的建议改变了getCertificateChain法显示波纹管

public X509Certificate[] getCertificateChain(String alias) { 
     X509Certificate[] chain = origKm.getCertificateChain(alias); 
     return chain; 
} 

public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) { 
        String alias; 

还我删除重复的方法,该方法.. 。

而在网瘾使用旧的信任存储的客户端不验证主机名

private static final HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() { 

    public boolean verify(String hostname, SSLSession session) { 
     return true; 
    } 
}; 

但对于那些需要使用第二信任存储做到这一点的验证客户端,这是一个原因,因为我需要处理与密钥对证书...

EDIT5

我想知道我怎么能实现服务器套接字让它能够与证书根据识别和使用 正确的证书正在使用的客户端,以继续进行 握手通信服务器。

解释更好,在服务器侧是:

AppServerSideSocket.jar

  • 专用密钥存储器:privateKeyApp(JKS类型,与密钥工具生成)
  • 公共密钥库:publicKeyApp(JKS型,与所有客户共享)

而且在客户端...

AppClientSideSocket.jar - 公共密钥库:publicKeyApp

AppServerSideSocket.jar监听客户端的请求,并通过客户端发送一次接收到的过程 信息

AppClientSideSocket.jar使用SSL使用SSL连接服务器publicKeyAppwithout 验证服务器主机名握手后发送AppServerSideSocket应用程序的信息。

现在我的另一个客户端应用程序,AppClientSideSocketNEW.jar,这验证服务器的主机名,以与服务器通信 。在这种情况下,客户端 的公共证书中使用的CN必须与AppServerSideSocket.jar所在的主机名匹配。

最初的连接被以这种方式配置服务器端:

if (usingSSLConn) { 
    System.setProperty("javax.net.ssl.keyStore", "privateKeyApp"); 
    System.setProperty("javax.net.ssl.keyStorePassword", "privateKeyAppPassword"); 

    SSLServerSocketFactory sslServerSocketFactory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); 
    ServerSocket serverSocketApp = sslServerSocketFactory.createServerSocket(Port); 

} else 
    serverSocketApp = new ServerSocket(Port); 
} 

所有的客户收到了同样的publicKeyApp,并没有验证主机服务器连接,所以不要紧 如果服务器在哪里服务器套接字应用程序(AppServerSideSocket.jar)安装在服务器上,主机名为 badServer1.com,并且privateKeyApp和publicKeyApp中的密钥的CN设置为goodServer1.com,因为所有的 客户端都不验证主机名或密钥的CN属性。

波纹管表现出了一块这种连接

private static final HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() { 

     public boolean verify(String hostname, SSLSession session) { 
      return true; 
     } 
}; 

System.setProperty("javax.net.ssl.trustStore", publicKey1); 
     System.getProperties().setProperty("java.protocol.handler.pkgs", "javax.net.ssl.internal.www.protocol"); 
    HttpsURLConnection.setDefaultHostnameVerifier(DO_NOT_VERIFY); 
    ... 
    SOAPConnectionFactory soapConn = SOAPConnectionFactory.newInstance(); 
    SOAPConnection connection = soapConn.createConnection(); 
    ...  
    URL endpoint = new URL(hostname + ":" + port); 

,但新的客户端(AppClientSideSocketNEW的。jar)强制执行此验证,现在有必要为此客户端提供一个新的证书 ,其CN属性的新值反映服务器套接字所在的正确主机名CN。

我没有访问第二个客户端,我确信它进行主机名验证。

所以我创建了两个新的密钥对证书(privateKeyAppNew和publicKeyAppNew),显然通信发生 使用使用这种新的公共publicKeyAppNew键这个新的密钥对和新的客户端服务器之间成功进行配置后,服务器使用这个新的密钥对当然。

但我需要继续为旧客户端使用旧的密钥对。我想知道我该如何处理这个问题。

使用keymanager让我能够在客户端尝试连接时验证服务器应用程序上的客户端证书,并选择合适的并使用正确的证书执行握手?

或者我需要在不同的端口有不同的ssl套接字连接为哪种客户端?

+0

你是说你想要根据客户端连接提供不同的证书吗?你也尝试使用客户端证书吗? – Bruno 2012-02-09 19:38:53

+1

[在SSL Socket Factory连接中使用多个密钥对]的可能重复(http://stackoverflow.com/questions/9179717/using-more-than-one-key-pair-in-ssl-socket-factory - 连接) – EJP 2012-02-10 00:42:00

+0

我认为你真的需要改善你的问题。从一开始就很混乱,但它并没有变得更好。请指定您的错误消息,并在哪一方获得他们(客户端或服务器)。不要尝试额外的东西,这些东西必然会导致额外的无关问题(例如,“我在Java 5 JRE上使用Java 6的代码”)。也许使用更有意义的日志消息(你的“回复到...”消息并不意味着它们是什么,因为你没有“回复”任何东西),请记录'remoteAddress.getHostAddress()'以确保这是你所期望的,以及它需要的分支。 – Bruno 2012-02-13 21:43:30

回答

1

简单的方法是将所有内容放在一个密钥存储区中 - 所有密钥和所有信任证书。这会消除你的问题。

+0

这并不能真正帮助选择使用哪个密钥/证书的问题。 – Bruno 2012-02-09 20:14:26

5

的“显而易见”的问题是,你实际上并没有做任何使用SSLContext S的创建:

SSLServerSocketFactory sslSrvSockFact = 
    (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); 

这至少应该是:

SSLServerSocketFactory sslSrvSockFact = 
    (SSLServerSocketFactory) ctx.getServerSocketFactory(); 

的问题是,你将不得不选择一个上下文或其他...

你的问题的解决方案是在the answer I gave to your other similar question a couple of days ago:你需要实现自己的X509KeyManager能够选择你要使用的密钥。

无论您是想使用单个密钥库还是从两个密钥库加载密钥/证书都没有多大关系:如果您确实想要,您当然可以实施getPrivateKeygetCertificateChain,以便它们从加载密钥/证书两个不同的密钥库取决于别名。尽管如此,这将是不必要的复杂。您仍然必须根据别名选择进行操作,因此您可以使用不同的别名从单个密钥存储区加载密钥/证书。

从服务器的角度来看,选择一个别名(以及密钥/证书对)的唯一方法是使用套接字(或引擎,如果使用的是X509ExtendedKeyManager)中提供的内容。由于Java 7不支持服务器名称指示(这会让客户端在选择过程之前知道它请求的是哪个主机名),您可能必须根据客户端IP地址或您的服务器IP地址正在使用(如果你有多个)。

Using two private keys (keystore) and two public keys (truststore)

您似乎对密钥库和信任库的内容感到困惑。除非您计划使用客户端证书身份验证,否则您可以忽略服务器上的信任存储设置。您可以使用默认(null)作为您的SSLContext.init(...)的第二个参数。您的“keystore(keystore)”是本地方(本例中为您的服务器)使用的信息,“truststore(keystore)”用于确定要信任哪个远程方。

您将要呈现给客户端的公钥(或将被精简的证书)也位于与您的私钥相关联的密钥库中,而不在信任库中。

编辑:

Exception in thread "main" java.lang.NoSuchMethodError: javax.net.ssl.SSLContext.setDefault(Ljavax/net/ssl/SSLContext;) at ...initialiseManager(499)

NoSuchMethodError

Thrown if an application tries to call a specified method of a class (either static or instance), and that class no longer has a definition of that method.

Normally, this error is caught by the compiler; this error can only occur at run time if the definition of a class has incompatibly changed.

这有什么,与你的SSL设置。不确定你在这里做了什么,但看起来你可能在Java 5 JRE上使用Java 6的代码(Java 6在SSLContext上没有setDefault)。更重要的是,你在这里使用Java的一般方式有些问题。

javax.net.ssl.SSLException:

No available certificate or key corresponds to the SSL cipher suites which are enabled.

这很可能由事实来解释:你似乎没有使用你已经在所有初始化的SSLContext小号...

  • 如果你有两对私钥/证书在您的密钥库中。

我的回答here仍然存在。我会尽量使它更加明确。我在这里假设您的一个证书/私钥使用alias1,另一个alias2。如果您不确定,请使用keyool -list查找。您可以选择并设置它们。

// Load the key store: change store type if needed 
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); 
FileInputStream fis = new FileInputStream("/path/to/keystore"); 
try { 
    ks.load(fis, keystorePassword); 
} finally { 
    if (fis != null) { fis.close(); } 
} 

// Get the default Key Manager 
KeyManagerFactory kmf = KeyManagerFactory.getInstance(
    KeyManagerFactory.getDefaultAlgorithm()); 
kmf.init(ks, keyPassword); 

final X509KeyManager origKm = (X509KeyManager)kmf.getKeyManagers()[0]; 
X509KeyManager km = new X509KeyManager() { 
    public String chooseServerAlias(String keyType, 
            Principal[] issuers, Socket socket) { 
     InetAddress remoteAddress = socket.getInetAddress(); 
     if (/* remoteAddress has some conditions you need to define yourself */ { 
      return "alias1"; 
     } else { 
      return "alias2"; 
     } 
    } 

    public String chooseClientAlias(String[] keyType, 
            Principal[] issuers, Socket socket) { 
     // Delegate this other methods to origKm. 
     origKm.chooseClientAlias(keyType, issuers, socket); 
    } 

    // Delegate this other methods to origKm, in the same way as 
    // it was done for chooseClientAlias. 
} 

SSLContext sslContext = SSLContext.getInstance("TLS"); 
sslContext.init(new KeyManager[] { km }, null, null); 

SSLSocketFactory sslSocketFactory = sslContext.getSSLSocketFactory(); 
  • 如果你真的想两个不同的密钥库。

做同样的,在此之上,在getCertificateChain(String alias),选择取决于别名使用的两个密钥库,并用它来获取证书链。 getPrivateKey(...)同样的事情。

+0

我可以使用客户端IP地址来选择正确的证书布鲁诺,例如...不是更容易使两个SSL /套接字连接,而不是? – Bera 2012-02-10 14:15:47

+0

@Bera,在我的例子中有一个拼写错误,'chooseServerAlias'显然(或者可能不是)重写了定义的方法(第一个参数是'String'),没有定义一个新的重载方法,并且使用String []作为第一个参数。另外,避免'getCertificateChain'中的复杂逻辑:只包装原来的密钥管理器并使用'alias'(最终,这并不重要,但是你使用了错误的参数名称,这可能导致更多的混淆) 。 – Bruno 2012-02-13 19:57:33

+0

除此之外,您应该知道客户提供的证书中的主机名(主题替换名称,或者如果CN中没有SAN),必须与客户端请求的内容匹配。 – Bruno 2012-02-13 19:58:23