我是Java和SSLSocket的新手。我想使用指定的.cer文件在客户端部分中建立SSLSocket。我在Google中搜索它,但是找不到很好的解决方案。这是我的代码:
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream caInput = new BufferedInputStream(new FileInputStream("myCer.cer"));
Certificate ca;
try {
ca = cf.generateCertificate(caInput);
System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
} finally {
caInput.close();
}
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
SSLSocket sock = (SSLSocket)context.getSocketFactory().createSocket("...",21000); //"...": here I ignore the host name. The address and port is right.
sock.setUseClientMode(true);
if(sock.isConnected()) {
System.out.println("Connected...");
}
else
{
System.out.println("Connect Fails...");
}
Login.pbLogin login = Login.pbLogin.newBuilder().setUserID("dbs")
.setPassword("abcd1234")
.setNewPassword("")
.setClientVersion("1.0.0.0")
.setRestarted(true)
.build();
OutputStream outputStream =sock.getOutputStream();
byte[] b1=login.getClass().getSimpleName().getBytes("UTF-8");
byte[] b2=login.toByteArray();
byte[] bytes = ByteBuffer.allocate(4).putInt(b1.length + b2.length).array();
outputStream.write(bytes);
outputStream.write(b1); //login.getClass().getSimpleName().getBytes("UTF-8")
outputStream.write(b2); //login.toByteArray()
outputStream.flush();
byte[] content = new byte[100];
int bytesRead = -1;
InputStream inputStream = sock.getInputStream();
String str;
while(( bytesRead = inputStream.read( content) ) != -1){
System.out.println("OK ,receive.....");
// str = new String(Arrays.copyOfRange(content,0,bytesRead), StandardCharsets.UTF_8);
//System.out.println(str);
}
我使用TCPViewer来查看,SSLSocket处于“已建立”状态,但是当执行outstream.write时,SSLsocket将处于“ Close_wait”状态并引起异常:
Exception in thread "main" java.net.SocketException: Software caused connection abort: socket write error.
所以我无法将信息写入服务器,然后退出程序。我猜想SSLSocket没有成功建立,但是Tcpviewer显示它建立得很早,并且它处于Connected状态(打印“ connected。”)。但是,当尝试编写输出流时,它将处于Close_wait状态。您能帮我解决一下吗?
最佳答案
然后我找到了今天的原因。代码没有问题,原因是服务器部分无法正确解析协议缓冲区(pblogin),这会导致异常,因此它关闭了套接字。结果,状态将为close_wait。既然找到原因,希望我自己解决。
关于java - java建立sslsocket使用.cer文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31558332/