在Java中使用SSL的Pkcs#11

时间:2017-05-18 07:34:57

标签: java ssl pkcs#11 softhsm

如何在java中使用pkcs#11和softhsm2进行ssl握手。 我正面临着使用softhsm2中存储的密钥实现ssl上下文工厂的问题。请提供我可以使用的样本。

1 个答案:

答案 0 :(得分:1)

这是pkcs#11在java中用于ssl握手的解决方案。

       System.setProperty("javax.net.debug", "ssl");
           try {
           String configName = "softhsm2.cfg";
           Provider p = new SunPKCS11(configName);
           System.out.println(p.getName());
           Security.addProvider(p);


           // Load the key store
           char[] pin = "5678".toCharArray();
           KeyStore ks = KeyStore.getInstance("PKCS11", p);
           ks.load(null, pin);
           System.out.println(ks.size());
          Enumeration<String> aliases = ks.aliases();
           for(;aliases.hasMoreElements();)
           {
            System.out.println(aliases.nextElement());
           }
           KeyManagerFactory keyManagerFactory =     KeyManagerFactory.getInstance("SunX509");
         //Add to keystore to key manager
           keyManagerFactory.init(ks, pin);  

         //Create the context

           SSLContext context = SSLContext.getInstance("TLS");
           context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());
            //Create a socket factory
           SSLServerSocketFactory ssf = context.getServerSocketFactory();
            //SSLSocketFactory sf = context.getSocketFactory();
           //Create the socket
            SSLServerSocket s   = (SSLServerSocket) ssf.createServerSocket(8888);
             printServerSocketInfo(s);
             SSLSocket c = (SSLSocket) s.accept();