一.双向验证
1.服务端
public class SSLServer extends Thread{
private static final int SERVER_PORT = 10002;
private static final String SERVER_KEYSTORE_PWD = "12345678";
private static final String SERVER_TRUST_KEYSTORE_PWD = "12345678";
private SSLServerSocket serverSocket;
public SSLServer() {
// Initialize SSLServer
try {
//Load KeyStore And TrustKeyStore
KeyStore keyStore = KeyStore.getInstance("JKS");
KeyStore trustKeyStore = KeyStore.getInstance("JKS");
try {
//服务端私钥
keyStore.load(new FileInputStream(
"./src/keyOfServer.keystore"),
SERVER_KEYSTORE_PWD.toCharArray());
//服务端信任列表,其中包括客户端证书
trustKeyStore.load(new FileInputStream(
"./src/trustOfServer.keystore"),
SERVER_TRUST_KEYSTORE_PWD.toCharArray());
} catch (CertificateException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Initialize KeyStore Factory 创建用于管理JKS密钥库的X.509密钥管理器
KeyManagerFactory keyManagerFactory =
KeyManagerFactory.getInstance("SunX509");
TrustManagerFactory trustManagerFactory =
TrustManagerFactory.getInstance("SunX509");
try {
keyManagerFactory.init(keyStore, SERVER_KEYSTORE_PWD.toCharArray());
} catch (UnrecoverableKeyException e) {
e.printStackTrace();
}
trustManagerFactory.init(trustKeyStore);
//Initialize SSLContext
SSLContext context = SSLContext.getInstance("SSL");
try {
//授权的密钥管理器,用来授权验证,
context.init(keyManagerFactory.getKeyManagers(),
trustManagerFactory.getTrustManagers(), null);
} catch (KeyManagementException e) {
e.printStackTrace();
}
//Set up Server Socket
try {
serverSocket = (SSLServerSocket) context.
getServerSocketFactory().createServerSocket(SERVER_PORT);
} catch (IOException e) {
e.printStackTrace();
}
serverSocket.setNeedClientAuth(true); //验证客户端证书
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
}
@Override
public void run() {
if(serverSocket == null){
System.out.println("Null server socket");
return;
}
while(true){
try {
Socket socket = serverSocket.accept();
//Response To Client
OutputStream output = socket.getOutputStream();
BufferedOutputStream bufferedOutput = new BufferedOutputStream(output);
bufferedOutput.write("Server Response: Hello".getBytes());
bufferedOutput.flush();
//Receive From Client
InputStream input = socket.getInputStream();
System.out.println("------Receive------");
//use byte array to initialize the output string
System.out.println(new String(StreamToByteArray(input)));
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* convert stream to Byte Array
* @param inputStream
* @return
* @throws IOException
*/
public byte[] StreamToByteArray(InputStream inputStream) throws IOException {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int readIndex = inputStream.read(buffer);
bout.write(buffer, 0, readIndex);
bout.flush();
bout.close();
inputStream.close();
return bout.toByteArray();
}
public static void main(String[] args){
System.out.println("=======Start Server !======");
new SSLServer().run();
}
}
2.客户端
public class SSLClient {
private static final String SERVER_HOST = "127.0.0.1";
private static final int SERVER_PORT = 10002;
private static final String CLIENT_KEYSTORE_PWD = "12345678";
private static final String CLIENT_TRUST_KEYSTORE_PWD = "12345678";
SSLSocket clientSocket;
public SSLClient(){
// Initialize SSLClient
try {
//Load KeyStore And TrustKeyStore
KeyStore keyStore = KeyStore.getInstance("JKS");
KeyStore trustKeyStore = KeyStore.getInstance("JKS");
try {
//client端密钥
keyStore.load(new FileInputStream(
"./src/keyOfClient.keystore"),
CLIENT_KEYSTORE_PWD.toCharArray());
//客户端的认证证书列表trustOfClient.keystore ,其中包括服务端证书
//从给定输入流中加载此 KeyStore
trustKeyStore.load(new FileInputStream(
"./src/trustOfClient.keystore"),
CLIENT_TRUST_KEYSTORE_PWD.toCharArray());
} catch (CertificateException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Initialize KeyStore Factory
KeyManagerFactory keyManagerFactory =
KeyManagerFactory.getInstance("SunX509");
//创建受信任管理器
TrustManagerFactory trustManagerFactory =
TrustManagerFactory.getInstance("SunX509");
try {
keyManagerFactory.init(keyStore, CLIENT_KEYSTORE_PWD.toCharArray());
} catch (UnrecoverableKeyException e) {
e.printStackTrace();
}
trustManagerFactory.init(trustKeyStore);
//Initialize SSLContext
SSLContext context = SSLContext.getInstance("SSL");
try {
context.init(keyManagerFactory.getKeyManagers(),
trustManagerFactory.getTrustManagers(), null);
} catch (KeyManagementException e) {
e.printStackTrace();
}
//Set up Client Socket
try {
clientSocket = (SSLSocket) context.
getSocketFactory().createSocket(SERVER_HOST, SERVER_PORT);
} catch (IOException e) {
e.printStackTrace();
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
}
private void Test() {
if(clientSocket == null){
System.out.println("NULL clientSocket");
return;
}
// Run Client Test
InputStream input = null;
OutputStream output = null;
try {
input = clientSocket.getInputStream();
output = clientSocket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
//Output Message To Server
BufferedOutputStream bufferedOutput = new BufferedOutputStream(output);
try {
//output to Server
bufferedOutput.write("Client Test Running".getBytes());
bufferedOutput.flush();
} catch (IOException e) {
e.printStackTrace();
}
//Output To Client Console
try {
System.out.println(new String(StreamToByteArray(input)));
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
// //close client socket
// try {
// clientSocket.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
}
/**
* convert stream to Byte Array
* @param inputStream
* @return
* @throws IOException
*/
public byte[] StreamToByteArray(InputStream inputStream) throws IOException {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int readIndex = inputStream.read(buffer);
bout.write(buffer, 0, readIndex);
bout.flush();
bout.close();
inputStream.close();
return bout.toByteArray();
}
public static void main(String[] args) {
new SSLClient().Test();
}
}
二、单向验证
1.服务端
public class SSLServer_Single extends Thread{
private static final int SERVER_PORT = 1234;
private static final String SERVER_KEYSTORE_PWD = "12345678";
private static final String SERVER_TRUST_KEYSTORE_PWD = "12345678";
private SSLServerSocket serverSocket;
public SSLServer_Single() {
// Initialize SSLServer
try {
//Load KeyStore And TrustKeyStore
//保存服务端的私钥
KeyStore keyStore = KeyStore.getInstance("JKS");
try {
//服务端私钥
keyStore.load(new FileInputStream(
"./src/keyOfServer.keystore"),
SERVER_KEYSTORE_PWD.toCharArray());
} catch (CertificateException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Initialize KeyStore Factory 创建用于管理JKS密钥库的X.509密钥管理器
KeyManagerFactory keyManagerFactory =
KeyManagerFactory.getInstance("SunX509");
try {
keyManagerFactory.init(keyStore, SERVER_KEYSTORE_PWD.toCharArray());
} catch (UnrecoverableKeyException e) {
e.printStackTrace();
}
//Initialize SSLContext
SSLContext context = SSLContext.getInstance("SSL");
try {
//授权的密钥管理器,用来授权验证,
context.init(keyManagerFactory.getKeyManagers(),
null, null);
} catch (KeyManagementException e) {
e.printStackTrace();
}
//Set up Server Socket
try {
serverSocket = (SSLServerSocket) context.
getServerSocketFactory().createServerSocket(SERVER_PORT);
serverSocket.setWantClientAuth(false); //不需要客户端证书
} catch (IOException e) {
e.printStackTrace();
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
}
@Override
public void run() {
if(serverSocket == null){
System.out.println("Null server socket");
return;
}
while(true){
try {
Socket socket = serverSocket.accept();
//Response To Client
OutputStream output = socket.getOutputStream();
BufferedOutputStream bufferedOutput = new BufferedOutputStream(output);
bufferedOutput.write("Server Response: Hello".getBytes());
bufferedOutput.flush();
//Receive From Client
InputStream input = socket.getInputStream();
System.out.println("------Receive------");
//use byte array to initialize the output string
System.out.println(new String(StreamToByteArray(input)));
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* convert stream to Byte Array
* @param inputStream
* @return
* @throws IOException
*/
public byte[] StreamToByteArray(InputStream inputStream) throws IOException {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int readIndex = inputStream.read(buffer);
bout.write(buffer, 0, readIndex);
bout.flush();
bout.close();
inputStream.close();
return bout.toByteArray();
}
public static void main(String[] args){
System.out.println("=======Start Server !======");
// new SSLServer().start();
new SSLServer_Single().run();
}
}
2.客户端
public class SSLClient_Single {
private static final String SERVER_HOST = "127.0.0.1";
private static final int SERVER_PORT = 1234;
private static final String CLIENT_KEYSTORE_PWD = "12345678";
private static final String CLIENT_TRUST_KEYSTORE_PWD = "12345678";
SSLSocket clientSocket;
public SSLClient_Single(){
// Initialize SSLClient
try {
//Load KeyStore And TrustKeyStore
//保存服务端的授权证书(服务端公钥)
KeyStore trustKeyStore = KeyStore.getInstance("JKS");
try {
//客户端的认证证书列表trustOfClient.keystore ,其中包括服务端证书
//从给定输入流中加载此 KeyStore
trustKeyStore.load(new FileInputStream(
"./src/trustOfClient.keystore"),
CLIENT_TRUST_KEYSTORE_PWD.toCharArray());
} catch (CertificateException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
TrustManagerFactory trustManagerFactory =
TrustManagerFactory.getInstance("SunX509");
trustManagerFactory.init(trustKeyStore);
//Initialize SSLContext
SSLContext context = SSLContext.getInstance("SSL");
try {
context.init(null,
trustManagerFactory.getTrustManagers(), null);
} catch (KeyManagementException e) {
e.printStackTrace();
}
//Set up Client Socket
try {
clientSocket = (SSLSocket) context.
getSocketFactory().createSocket(SERVER_HOST, SERVER_PORT);
} catch (IOException e) {
e.printStackTrace();
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
}
private void Test() {
if(clientSocket == null){
System.out.println("NULL clientSocket");
return;
}
// Run Client Test
InputStream input = null;
OutputStream output = null;
try {
input = clientSocket.getInputStream();
output = clientSocket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
//Output Message To Server
BufferedOutputStream bufferedOutput = new BufferedOutputStream(output);
try {
//output to Server
bufferedOutput.write("Client Test Running".getBytes());
bufferedOutput.flush();
} catch (IOException e) {
e.printStackTrace();
}
//Output To Client Console
try {
System.out.println(new String(StreamToByteArray(input)));
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
// //close client socket
// try {
// clientSocket.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
}
/**
* convert stream to Byte Array
* @param inputStream
* @return
* @throws IOException
*/
public byte[] StreamToByteArray(InputStream inputStream) throws IOException {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int readIndex = inputStream.read(buffer);
bout.write(buffer, 0, readIndex);
bout.flush();
bout.close();
inputStream.close();
return bout.toByteArray();
}
public static void main(String[] args) {
new SSLClient_Single().Test();
}
}
三、证书