java sslsocket程序_JAVA与C++进行sslsocket通信,JAVA做服务端或客户端
前幾天有位網(wǎng)友問我關(guān)于Unity3D里面使用Protobuf的方法,一時(shí)有事拖到現(xiàn)在才寫這篇文章,不好意思哈。 本文測試環(huán)境: 系統(tǒng):WINDOWS 7(第3、6步)、OS X 10.9(第4步) 軟件:VS 2012(第3、6步)、Eclipse(第5、6步) 硬件:iPad 2(第4步)、Macbook Pro
一、JAVA做服務(wù)端,讀取pem格式的證書和秘鑰 public class SocketServer extends Thread{
private static final int SERVER_PORT = 10002;
private SSLServerSocket serverSocket;
public SocketServer() {
// Initialize SSLServer
try {
//Load KeyStore And TrustKeyStore
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
//保存服務(wù)端的私鑰
KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(null, null);//
// 讀入服務(wù)端證書
PEMReader cacertfile = new PEMReader(new InputStreamReader(
new FileInputStream("d:/cacert.pem")));
X509Certificate cacert = (X509Certificate) cacertfile.readObject();
Certificate[] certChain = new Certificate[1];
certChain[0] = cacert;
cacertfile.close();
// 讀入私鑰
PEMReader kr = new PEMReader(new InputStreamReader(new FileInputStream("d:/privkey.pem")));
KeyPair key = (KeyPair) kr.readObject();
kr.close();
// 導(dǎo)入服務(wù)端端私鑰和證書
keyStore.setKeyEntry("serverkey", key.getPrivate(), new char[]{}, certChain );
keyStore.setCertificateEntry("servercert", cacert);
//Initialize KeyStore Factory
創(chuàng)建用于管理JKS密鑰庫的X.509密鑰管理器
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
keyManagerFactory.init(keyStore, "".toCharArray());
//Initialize SSLContext
SSLContext context = SSLContext.getInstance("TLSv1");
//授權(quán)的密鑰管理器,用來授權(quán)驗(yàn)證,
context.init(keyManagerFactory.getKeyManagers(), null, null);
//Set up Server Socket
serverSocket = (SSLServerSocket) context.
getServerSocketFactory().createServerSocket(SERVER_PORT);
serverSocket.setWantClientAuth(false); //不需要客戶端證書
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void run() {
if(serverSocket == null){
System.out.println("Null server socket");
return;
}
try {
Socket socket = serverSocket.accept();
//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)));
if(!socket.isClosed()){
//Response To Client
OutputStream output = socket.getOutputStream();
output.write("服務(wù)端發(fā)送123".getBytes());
output.flush();
socket.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){
System.out.println("=======Start Server !======");
new SocketServer().run();
}} 二、JAVA做客戶端,讀取pem格式證書和秘鑰 public class SocketClient2 {
private Logger logger = LoggerFactory.getLogger(SocketClient2.class);
private String tpath = Tools.getConfig("簡述: 建立簡單的server與client,在利用socket上通信 知識點(diǎn): 1. java socket 通信 2. java GUI的幾個(gè)控件 3. 多線程并發(fā) 代碼: SimpleChatServer.java [java]
view plain copy package?test.chatclient;
import?java.io.*;
import?java.net.*;KeyPath");// 證書路徑
private String ip = Tools.getConfig("ip");// 服務(wù)端ip
private int port = Integer.parseInt(Tools.getConfig("port"));// 端口
public static List socketList = new ArrayList();
public SSLSocket getSSlSocket() {
SSLContext context = null;
context = this.getSSLcontext();
SSLSocketFactory ssf = context.getSocketFactory();
try {
SSLSocket ss = (SSLSocket) ssf.createSocket("127.0.0.1", 10002);
String[] protocols = { "TLSv1" }; //設(shè)置客戶端協(xié)議
ss.setEnabledProtocols(protocols);
return ss;
} catch (UnknownHostException e) {
logger.error("a{}", e);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private SSLContext getSSLcontext() {
SSLContext sslContext = null;
try {
// 設(shè)定Security的Provider提供程序
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());//
System.setProperty("https.protocols", "SSLv3,SSLv2Hello");
// 建立空BKS,android只能用BKS(BouncyCastle密庫),一般java應(yīng)用參數(shù)傳JKS(java自帶密庫)
//訪問Java密鑰庫,JKS是keytool創(chuàng)建的Java密鑰庫,保存密鑰。
KeyStore ksKeys = KeyStore.getInstance("JKS");
ksKeys.load(null, null);
// 讀入客戶端證書
PEMReader cacertfile = new PEMReader(new InputStreamReader(
new FileInputStream("d:/cacert.pem")));
X509Certificate cacert = (X509Certificate) cacertfile.readObject();
cacertfile.close();
// 導(dǎo)入根證書作為trustedEntry
//KeyStore.TrustedCertificateEntry
保存可信的 Certificate 的 KeyStore 項(xiàng)。
KeyStore.TrustedCertificateEntry trustedEntry = new KeyStore.TrustedCertificateEntry(
cacert);
//用指定別名保存 keystore Entry。
ksKeys.setEntry("ca_root", trustedEntry, null);
// 構(gòu)建TrustManager
創(chuàng)建用于管理JKS密鑰庫的X.509密鑰管理器。
TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");// 密鑰管理器
tmf.init(ksKeys);
// 構(gòu)建SSLContext,此處傳入?yún)?shù)為TLS,也可以為SSL
sslContext = SSLContext.getInstance("TLSv1");
sslContext.init(null, tmf.getTrustManagers(), null);
} catch (Exception e) {
e.printStackTrace();
}
return sslContext;
}
public static void main(String[] args) {
SocketClient2 client = new SocketClient2();
SSLSocket ss =client.getSSlSocket();
try {
ss.setSoTimeout(2000);
OutputStream socketOut = null;
if (ss != null && !ss.isClosed()) {
socketOut = ss.getOutputStream();
socketOut.write("客戶端發(fā)送".getBytes());
socketOut.flush();
}
if (ss != null && !ss.isClosed()) {
InputStream in;
in = ss.getInputStream();
//input中的數(shù)據(jù)只能讀取一次
System.out.println(new String(StreamToByteArray(in)));
}
ss.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* convert stream to Byte Array
* @param inputStream
* @return
* @throws IOException
*/
public static 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();
return bout.toByteArray();
}
} 三、證書
注:此服務(wù)端和客戶端可以進(jìn)行通信也可與C++進(jìn)行通信。
總結(jié)
以上是生活随笔為你收集整理的java sslsocket程序_JAVA与C++进行sslsocket通信,JAVA做服务端或客户端的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 男性不育的症状表现有哪些
- 下一篇: 柯基犬多少钱啊?