java网络编程5-SSL
服务器端
System.out.println("等待客户端连接...");File keyFile=new File("C:/Users/mu/Desktop/mu.p12");
InputStream stream=new FileInputStream(keyFile);
char[] password="123456".toCharArray();
//KeyStore用于存放证书,创建对象时 指定交换数字证书的加密标准
KeyStore keyStore=KeyStore.getInstance("pkcs12"); //KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(stream, password);
stream.close();
//KeyManager选择证书证明自己的身份
KeyManagerFactory keyManagerFactory=KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore,password);
KeyManager[] keyManagers=keyManagerFactory.getKeyManagers();
//TrustManager决定是否信任对方的证书
TrustManagerFactory trustManagerFactory=TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
TrustManager[] trustManagers=trustManagerFactory.getTrustManagers();
SSLContext context=SSLContext.getInstance("SSL");
context.init(keyManagers, trustManagers, null);
SSLServerSocketFactory factory=context.getServerSocketFactory();
SSLServerSocket serverSocket=(SSLServerSocket)factory.createServerSocket(3344);
SSLSocket socket=(SSLSocket)serverSocket.accept();
System.out.println("有客户端连接");
System.out.println("向客户端输出信息");
OutputStream outputStream=socket.getOutputStream();
BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(outputStream));
writer.write("hello world\r\n");
writer.write("\r\n");
writer.flush();
System.out.println("输出结束");
socket.close();
serverSocket.close();
客户端
System.out.println("准备连接服务端");File keyFile=new File("C:/Users/mu/Desktop/mu.p12");
InputStream stream=new FileInputStream(keyFile);
char[] password="123456".toCharArray();
//指定交换数字证书的加密标准
KeyStore keyStore= KeyStore.getInstance("pkcs12");//KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(stream, password);
stream.close();
//TrustManager决定是否信任对方的证书
TrustManagerFactory trustManagerFactory=TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
TrustManager[] trustManagers=trustManagerFactory.getTrustManagers();
SSLContext context=SSLContext.getInstance("SSL");
context.init(null, trustManagers, null);
SSLSocketFactory factory=context.getSocketFactory();
SSLSocket socket=(SSLSocket) factory.createSocket("localhost", 3344);
InputStream inputStream=socket.getInputStream();
BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream));
String str=null;
while ((str=reader.readLine())!=null) {
if(str.equals(""))
break;
System.out.println(str);
}
socket.close();
以上是 java网络编程5-SSL 的全部内容, 来源链接: utcz.com/z/390861.html