JAVA与C++进行sslsocket通信,JAVA做服务端或客户端
2016-01-02 18:44
681 查看
一、JAVA做服务端,读取pem格式的证书和秘钥
三、证书
注:此服务端和客户端可以进行通信也可与C++进行通信。
<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++进行通信。
相关文章推荐
- C语言指针-----指针与文件
- [ 1011] 注释转换 C++到C的几种情况
- [1010] C注释转c++
- C语言数组与字符串初始化
- 动态数组分配(C语言)
- MFC VC++6.0列表控件的使用
- C++对象在内存中的存储
- 黑马程序员-C语言-小知识点集
- C语言基础之内存分配
- 观察者模式
- C++中导致二义性错误
- C++命名空间
- C/C++数据对齐方式
- 黑马程序员-C语言-数组名作为函数参数
- 手把手教你学单片机--51单片机C语言开发
- Turbo C++ 3.0创建多文件项目的方法
- 利用C++11实现一个自动注册的工厂
- C++小题(八)
- 手把手教你学单片机--51单片机C语言开发
- C语言实现程序开机自启动