我的密钥库中有一个客户端证书,而我的信任库中有一个服务器的公共证书。
当前,我将我的密钥库和信任库设置为
System.setProperty("javax.net.ssl.keyStoreType", "pkcs12");
System.setProperty("javax.net.ssl.keyStore", Constants.APPLICATION_HOME + File.separatorChar + this.certificateName);
System.setProperty("javax.net.ssl.keyStorePassword", certificatePass);
System.setProperty("javax.net.ssl.trustStore", Constants.APPLICATION_HOME + File.separatorChar + "jssecacerts");
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
System.setProperty("javax.net.ssl.trustStoreType", "JKS");
但是我想不使用System.setProperty()
来做。至少密钥库部分,信任库可以保持这种状态,因为它永远不会改变。我尝试过:
keyStore = KeyStore.getInstance("PKCS12");
InputStream keyStoreData = new FileInputStream(Constants.APPLICATION_HOME + File.separatorChar + this.certificateName);
this.keyStore.load(keyStoreData, certificatePass.toCharArray());
TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustFactory.init(this.keyStore);
TrustManager[] trustManagers = trustFactory.getTrustManagers();
sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustManagers, null);
SSLContext.setDefault(sslContext);
但是据我所知,这正在设置信任库,因此握手失败,因为现在我的信任库中只有客户端证书,而从jssecacerts文件中没有服务器证书。它因以下错误而失败:
http-bio-8080-exec-10,处理异常: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException:PKIX路径构建失败: sun.security.provider.certpath.SunCertPathBuilderException:无法执行 找到到所请求目标的有效认证路径
我该如何实现?
答案 0 :(得分:1)
此示例可以为您提供帮助:
import java.io.File;
import java.io.FileInputStream;
import java.net.InetAddress;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.security.KeyStore;
import org.java_websocket.server.DefaultSSLWebSocketServerFactory;
public class EventWebSocketSecureServer extends EventWebSocketServer {
private static EventWebSocketSecureServer instance;
public static EventWebSocketSecureServer instance() {
return instance;
}
public EventWebSocketSecureServer(int port, InetAddress ip) {
this(port, null, null, ip);
}
public EventWebSocketSecureServer(int port, String keystorepath, String keystorepassword, InetAddress ip) {
super(port, ip);
try {
SSLContext sslContext = SSLContext.getInstance("TLS");
char ksPassword[] = keystorepassword.toCharArray();
if (!keystorepath.equals("")) {
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream(new File(keystorepath)), ksPassword);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, ksPassword);
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(ks);
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
} else {
sslContext.init(null, null, null);
}
this.setWebSocketFactory(new DefaultSSLWebSocketServerFactory(sslContext));
} catch (Exception e) {
com.gmt2001.Console.out.println("Secure EventSocketServer failed: " + e);
e.printStackTrace();
}
}
}