服务器端代码:
import java.net.*;
import javax.net.ssl.*;
import java.io.*;
import java.security.*;
public class SSLServer {
private static int port = 50003;
private static SSLServerSocket server;
public static void initSSLServerSocket() {
try {
/** 要使用的证书名 **/
String cert = "\\key.cert";
/** 要使用的证书密码 **/
char certPass[] = "123456".toCharArray();
/** 证书别称所使用的主要密码 **/
char certAliaMainPass[] = "123456".toCharArray();
/** 创建JKS密钥库 **/
KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(new FileInputStream(cert), certPass);
/** 创建管理JKS密钥库的X.509密钥管理器 **/
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
keyManagerFactory.init(keyStore, certAliaMainPass);
SSLContext sslContext = SSLContext.getInstance("TLSV1");
/** 想使用SSL时,更改成如下,注释部分 **/
//SSLContext sslContext = SSLContext.getInstance("SSLV3");
sslContext.init(keyManagerFactory.getKeyManagers(), null, null);
SSLServerSocketFactory sslServerSocketFactory = sslContext.getServerSocketFactory();
server = (SSLServerSocket) sslServerSocketFactory.createServerSocket(port);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
try {
initSSLServerSocket();
System.out.println("服务器在端口 [" + port + "] 等待连接...");
while (true) {
SSLSocket socket = (SSLSocket) server.accept();
new CreateThread(socket);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class CreateThread extends Thread {
private static BufferedReader in;
private static PrintWriter out;
private static Socket s;
public CreateThread(Socket socket) {
try {
s = socket;
in = new BufferedReader(new InputStreamReader(s.getInputStream(), "GB2312"));
out = new PrintWriter(s.getOutputStream(), true);
start();
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
try {
String msg = in.readLine();
System.out.println("接收到: " + msg);
out.write("服务器接收到的信息是: " + msg);
out.flush();
s.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
客户端代码:
import java.net.*;
import javax.net.ssl.*;
import java.io.*;
public class SSLClient {
static int port = 50003;
public static void main(String args[]) {
try {
SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
Socket s = factory.createSocket("192.168.12.41", port);
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream(), "GB2312"));
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
out.println("证书启用成功!");
System.out.println(in.readLine());
out.close();
s.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
服务器启动:java SSLServer
key.cert 文件需要和 SSLServer.class 同一目录下
客户端运行:java -Djavax.net.ssl.trustStore=key.cert SSLClient
key文件生成:keytool -genkey -keystore Key.cert -keyalg rsa –alias tempkey
或者: keytool -genkey -alias tempkey -keysize 512 -validity 3650 -keyalg RSA -dname "CN=sariel.iteye.com, OU=sariel CA, O=sariel Inc, L=Stockholm, S=Stockholm, C=SE" -keypass 123456 -storepass 123456 -keystore key.cert