您的位置:首页 > 编程语言 > C语言/C++

JAVA与C++进行sslsocket通信,JAVA做服务端或客户端

2016-01-02 18:44 681 查看
一、JAVA做服务端,读取pem格式的证书和秘钥

<span style="font-size:18px;">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());
//保存服务端的私钥
KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(null, null);
//			// 读入服务端证书
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();
// 导入服务端端私钥和证书
keyStore.setKeyEntry("serverkey", key.getPrivate(), new char[]{}, certChain );
keyStore.setCertificateEntry("servercert", cacert);
//Initialize KeyStore Factory   创建用于管理JKS密钥库的X.509密钥管理器
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
keyManagerFactory.init(keyStore, "".toCharArray());
//Initialize SSLContext
SSLContext context = SSLContext.getInstance("TLSv1");
//授权的密钥管理器,用来授权验证,
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("服务端发送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();
}
}
</span>
二、JAVA做客户端,读取pem格式证书和秘钥

<span style="font-size:18px;">public class SocketClient2 {

private Logger logger = LoggerFactory.getLogger(SocketClient2.class);
private String tpath = Tools.getConfig("KeyPath");// 证书路径
private String ip = Tools.getConfig("ip");// 服务端ip
private int port = Integer.parseInt(Tools.getConfig("port"));// 端口
public static List<SSLSocket> socketList = new ArrayList<SSLSocket>();

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" }; //设置客户端协议
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 {
// 设定Security的Provider提供程序
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
//			System.setProperty("https.protocols", "SSLv3,SSLv2Hello");
// 建立空BKS,android只能用BKS(BouncyCastle密库),一般java应用参数传JKS(java自带密库)
//访问Java密钥库,JKS是keytool创建的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();
// 导入根证书作为trustedEntry
//KeyStore.TrustedCertificateEntry  保存可信的 Certificate 的 KeyStore 项。
KeyStore.TrustedCertificateEntry trustedEntry = new KeyStore.TrustedCertificateEntry(
cacert);
//用指定别名保存 keystore Entry。
ksKeys.setEntry("ca_root", trustedEntry, null);
// 构建TrustManager   创建用于管理JKS密钥库的X.509密钥管理器。
TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");// 密钥管理器
tmf.init(ksKeys);
// 构建SSLContext,此处传入参数为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("客户端发送".getBytes());
socketOut.flush();
}
if (ss != null && !ss.isClosed()) {
InputStream in;
in = ss.getInputStream();
//input中的数据只能读取一次
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();
}
}
</span>


三、证书




注:此服务端和客户端可以进行通信也可与C++进行通信。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: