没有“服务器”的Java双向SSL

时间:2014-07-16 16:21:45

标签: java ssl mutual-authentication

我一直在寻找java中的相互身份验证SSL的例子,其中没有像weblogic / glassfish / tomcat /等那样的“服务器” - 是否有这样的事情?

也请不要使用外部库,我希望能够满足以下要求:

import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;

1 个答案:

答案 0 :(得分:2)

您可以使用类似的内容(请注意,这来自我所做的教程学校项目,而且不完整)

客户端

    //load client private key
    KeyStore clientKeys = KeyStore.getInstance("JKS");
    clientKeys.load(new FileInputStream("proxyKeystore"),"password".toCharArray());
    KeyManagerFactory clientKeyManager = KeyManagerFactory.getInstance("SunX509");
    clientKeyManager.init(clientKeys,"password".toCharArray());
    //load server public key
    KeyStore serverPub = KeyStore.getInstance("JKS");
    serverPub.load(new FileInputStream("proxyTrustedStore"),"password".toCharArray());
    TrustManagerFactory trustManager = TrustManagerFactory.getInstance("SunX509");
    trustManager.init(serverPub);

  //use keys to create SSLSoket
  SSLContext ssl = SSLContext.getInstance("TLS");
  ssl.init(clientKeyManager.getKeyManagers(), trustManager.getTrustManagers(), SecureRandom.getInstance("SHA1PRNG"));
  socket = (SSLSocket)ssl.getSocketFactory().createSocket("localhost", 8889);


  socket.startHandshake();

服务器:

KeyStore serverKeys = KeyStore.getInstance("JKS");
            serverKeys.load(new FileInputStream("authKeystore"),"password".toCharArray());
            KeyManagerFactory serverKeyManager = KeyManagerFactory.getInstance("SunX509");
            serverKeyManager.init(serverKeys,"password".toCharArray());


            KeyStore clientPub = KeyStore.getInstance("JKS");
            clientPub.load(new FileInputStream("authTrustedStore"),"password".toCharArray());
            TrustManagerFactory trustManager = TrustManagerFactory.getInstance("SunX509");
            trustManager.init(clientPub);

          //use keys to create SSLSoket
          SSLContext ssl = SSLContext.getInstance("TLS");
          ssl.init(serverKeyManager.getKeyManagers(), trustManager.getTrustManagers(), SecureRandom.getInstance("SHA1PRNG"));
          serverSock = (SSLServerSocket)ssl.getServerSocketFactory().createServerSocket(8889);
          serverSock.setNeedClientAuth(true);
          socket = (SSLSocket)serverSock.accept();

在开始握手和/或接受serverSocket连接之前,您可以从服务器和/或客户端请求证书。