我需要从安卓手机通过 SSLSocket(不是 http/https)连接服务器。我首先生成了带有私有/公共对的 jks 密钥库,然后生成了一个只有客户端公钥的 jks。然后我首先尝试将 SSLSocketFactory 从 java 设置为 java,然后我让它工作。Android 不接受我的 jks 密钥库,因此我将其转换为 bks 用于 android 端。但是,当我测试它时,服务器端会抛出一个
javax.net.ssl.SSLHandshakeException: Received fatal alert: certificate_unknown
android端抛出一个
java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
这是测试服务器的代码:
System.setProperty("javax.net.ssl.keyStore","edkey.jks");
System.setProperty("javax.net.ssl.keyStorePassword","password");
ServerSocketFactory ssocketFactory = SSLServerSocketFactory.getDefault();
ServerSocket ssocket = ssocketFactory.createServerSocket(port);
System.out.println(ansiPurple("Starting"));
socket = ssocket.accept();
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
....
以下是工作 Java 客户端的代码:
System.setProperty("javax.net.ssl.trustStore","edkey_public.jks");
System.setProperty("javax.net.ssl.trustStorePassword","password");
SSLSocketFactory f = (SSLSocketFactory)SSLSocketFactory.getDefault();
socket = (SSLSocket)f.createSocket(host, port);
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
....
这是不工作的android应用程序的代码:
InputStream ki = a.getResources().openRawResource(a.getResources().getIdentifier("raw/edkey_public", "raw", a.getPackageName()));
KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
KeyStore ks = KeyStore.getInstance("BKS");
ks.load(ki,"password".toCharArray());
kmfactory.init(ks, "password".toCharArray());
ki.close();
KeyManager[] keymanagers = kmfactory.getKeyManagers();
TrustManagerFactory tmf=TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
TrustManager[] tms = tmf.getTrustManagers();
SSLContext sslContext=SSLContext.getInstance("TLSv1.2");
sslContext.init(keymanagers, tms, new SecureRandom());
SSLSocketFactory f=sslContext.getSocketFactory();
Socket socket = (SSLSocket)f.createSocket(host, port);
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
....
有谁知道问题出在哪里?