GVKun编程网logo

SSL 握手通信详解及 linux 下 c/c++ SSL Socket 代码举例 (另附 SSL 双向认证客户端代码)

9

在本文中,我们将详细介绍SSL握手通信详解及linux下c/c++SSLSocket代码举例(另附SSL双向认证客户端代码)的各个方面,同时,我们也将为您带来关于HttpClient4实现SSL双向认

在本文中,我们将详细介绍SSL 握手通信详解及 linux 下 c/c++ SSL Socket 代码举例 (另附 SSL 双向认证客户端代码)的各个方面,同时,我们也将为您带来关于HttpClient4实现SSL双向认证的客户端(一)、HttpClient4实现SSL双向认证的客户端(二)、IO :: Socket :: SSL似乎忽略了SSL_VERIFY_NONE、java keystore 实现ssl双向认证【客户端为php和java】的有用知识。

本文目录一览:

SSL 握手通信详解及 linux 下 c/c++ SSL Socket 代码举例 (另附 SSL 双向认证客户端代码)

SSL 握手通信详解及 linux 下 c/c++ SSL Socket 代码举例 (另附 SSL 双向认证客户端代码)

SSL 握手通信详解及 linux 下 c/c++ SSL Socket 代码举例 (另附 SSL 双向认证客户端代码)

摘自: https://blog.csdn.net/sjin_1314/article/details/21043613

2014 年 03 月 11 日 22:02:14  轻飘风扬  阅读数:19886
 

SSL (Secure Sockets Layer 安全套接层), 及其继任者传输层安全(Transport Layer Security,TLS)是为网络通信提供安全及数据完整性的一种安全协议。TLS 与 SSL 在传输层对网络连接进行加密。

  安全证书既包含了用于加密数据的密钥,又包含了用于证实身份的数字签名。安全证书采用公钥加密技术。公钥加密是指使用一对非对称的密钥进行加密或解密。每一对密钥由公钥和私钥组成。公钥被广泛发布。私钥是隐秘的,不公开。用公钥加密的数据只能够被私钥解密。反过来,使用私钥加密的数据只能被公钥解密。这个非对称的特性使得公钥加密很有用。在安全证书中包含着一对非对称的密钥。只有安全证书的所有者才知道私钥。当通信方 A 将自己的安全证书发送给通信方 B 时,实际上发给通信方 B 的是公开密钥,接着通信方 B 可以向通信方 A 发送用公钥加密的数据,只有通信方 A 才能使用私钥对数据进行解密,从而获得通信方 B 发送的原始数据。安全证书中的数字签名部分是通信方 A 的电子身份证。数字签名告诉通信方 B 该信息确实由通信方 A 发出,不是伪造的,也没有被篡改。

  客户与服务器通信时,首先要进行 SSL 握手,SSL 握手主要完成以下任务:

  1) 协商使用的加密套件。加密套件中包括一组加密参数,这些参数指定了加密算法和密钥的长度等信息。

  2) 验证对方的身份,此操作是可选的。

  3) 确定使用的加密算法。

  4) SSL 握手过程采用非对称加密方法传递数据,由此来建立一个安全的 SSL 会话。SSL 握手完成后,通信双方将采用对称加密方法传递实际的应用数据。

   以下是 SSL 握手的具体流程:

(1)客户将自己的 SSL 版本号、加密参数、与 SSL 会话有关的数据及其他一些必要信息发送到服务器。

(2)服务器将自己的 SSL 版本号、加密参数、与 SSL 会话有关的数据及其他一些必要信息发送给客户,同时发给客户的还有服务器的证书。如果服务器需要验证客户身份,服务器还会发出要求客户提供安全证书的请求。

(3)客户端验证服务器证书,如果验证失败,就提示不能建立 SSL 连接。如果成功,那么继续下一步骤。

(4)客户端为本次 SSL 会话生成预备主密码(pre-master secret),并将其用服务器公钥加密后发送给服务器。

(5)如果服务器要求验证客户身份,客户端还要对另外一些数据签名后,将其与客户端证书一起发送给服务器。

(6)如果服务器要求验证客户身份,则检查签署客户证书的 CA(Certificate Authority,证书机构)是否可信。如果不在信任列表中,结束本次会话。如果检查通过,服务器用自己的私钥解密收到的预备主密码(pre-master secret),并用它通过某些算法生成本次会话的主密码(master secret)。

(7)客户端与服务器端均使用此主密码(master secret)生成此次会话的会话密钥(对称密钥)。在双方 SSL 握手结束后传递任何消息均使用此会话密钥。这样做的主要原因是对称加密比非对称加密的运算量要低一个数量级以上,能够显著提高双方会话时的运算速度。

(8)客户端通知服务器此后发送的消息都使用这个会话密钥进行加密,并通知服务器客户端已经完成本次 SSL 握手。

(9)服务器通知客户端此后发送的消息都使用这个会话密钥进行加密,并通知客户端服务器已经完成本次 SSL 握手。

(10)本次握手过程结束,SSL 会话已经建立。在接下来的会话过程中,双方使用同一个会话密钥分别对发送和接收的信息进行加密和解密。

以下为 linux c/c++ SSL socket Client 和 Server 的代码参考。

 客户端代码如下:

  1.  
    /*File: client_ssl.c
  2.  
    *Auth:sjin
  3.  
    *Date:2014-03-11
  4.  
    *
  5.  
    */
  6.  
     
  7.  
     
  8.  
    #include <stdio.h>
  9.  
    #include <string.h>
  10.  
    #include <errno.h>
  11.  
    #include <sys/socket.h>
  12.  
    #include <resolv.h>
  13.  
    #include <stdlib.h>
  14.  
    #include <netinet/in.h>
  15.  
    #include <arpa/inet.h>
  16.  
    #include <unistd.h>
  17.  
    #include <sys/types.h>
  18.  
    #include <sys/stat.h>
  19.  
    #include <fcntl.h>
  20.  
    #include <openssl/ssl.h>
  21.  
    #include <openssl/err.h>
  22.  
     
  23.  
    #define MAXBUF 1024
  24.  
     
  25.  
    void ShowCerts(SSL * ssl)
  26.  
    {
  27.  
    X509 *cert;
  28.  
    char *line;
  29.  
     
  30.  
    cert = SSL_get_peer_certificate(ssl);
  31.  
    if (cert != NULL) {
  32.  
    printf( "Digital certificate information:\n");
  33.  
    line = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0);
  34.  
    printf( "Certificate: %s\n", line);
  35.  
    free(line);
  36.  
    line = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0);
  37.  
    printf( "Issuer: %s\n", line);
  38.  
    free(line);
  39.  
    X509_free(cert);
  40.  
    }
  41.  
    else
  42.  
    printf( "No certificate information!\n");
  43.  
    }
  44.  
     
  45.  
    int main(int argc, char **argv)
  46.  
    {
  47.  
    int i,j,sockfd, len, fd, size;
  48.  
    char fileName[ 50],sendFN[ 20];
  49.  
    struct sockaddr_in dest;
  50.  
    char buffer[MAXBUF + 1];
  51.  
    SSL_CTX *ctx;
  52.  
    SSL *ssl;
  53.  
     
  54.  
    if (argc != 3)
  55.  
    {
  56.  
    printf( "Parameter format error! Correct usage is as follows:\n\t\t%s IP Port\n\tSuch as:\t%s 127.0.0.1 80\n", argv[ 0], argv[ 0]); exit( 0);
  57.  
    }
  58.  
     
  59.  
    /* SSL 库初始化 */
  60.  
    SSL_library_init();
  61.  
    OpenSSL_add_all_algorithms();
  62.  
    SSL_load_error_strings();
  63.  
    ctx = SSL_CTX_new(SSLv23_client_method());
  64.  
    if (ctx == NULL)
  65.  
    {
  66.  
    ERR_print_errors_fp( stdout);
  67.  
    exit( 1);
  68.  
    }
  69.  
     
  70.  
    /* 创建一个 socket 用于 tcp 通信 */
  71.  
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
  72.  
    {
  73.  
    perror( "Socket");
  74.  
    exit(errno);
  75.  
    }
  76.  
    printf( "socket created\n");
  77.  
     
  78.  
    /* 初始化服务器端(对方)的地址和端口信息 */
  79.  
    bzero(&dest, sizeof(dest));
  80.  
    dest.sin_family = AF_INET;
  81.  
    dest.sin_port = htons(atoi(argv[ 2]));
  82.  
    if (inet_aton(argv[ 1], (struct in_addr *) &dest.sin_addr.s_addr) == 0)
  83.  
    {
  84.  
    perror(argv[ 1]);
  85.  
    exit(errno);
  86.  
    }
  87.  
    printf( "address created\n");
  88.  
     
  89.  
    /* 连接服务器 */
  90.  
    if (connect(sockfd, (struct sockaddr *) &dest, sizeof(dest)) != 0)
  91.  
    {
  92.  
    perror( "Connect ");
  93.  
    exit(errno);
  94.  
    }
  95.  
    printf( "server connected\n\n");
  96.  
     
  97.  
    /* 基于 ctx 产生一个新的 SSL */
  98.  
    ssl = SSL_new(ctx);
  99.  
    SSL_set_fd(ssl, sockfd);
  100.  
    /* 建立 SSL 连接 */
  101.  
    if (SSL_connect(ssl) == -1)
  102.  
    ERR_print_errors_fp( stderr);
  103.  
    else
  104.  
    {
  105.  
    printf( "Connected with %s encryption\n", SSL_get_cipher(ssl));
  106.  
    ShowCerts(ssl);
  107.  
    }
  108.  
     
  109.  
    /* 接收用户输入的文件名,并打开文件 */
  110.  
    printf( "\nPlease input the filename of you want to load :\n>");
  111.  
    scanf( "%s",fileName);
  112.  
    if((fd = open(fileName,O_RDONLY, 0666))< 0)
  113.  
    {
  114.  
    perror( "open:");
  115.  
    exit( 1);
  116.  
    }
  117.  
     
  118.  
    /* 将用户输入的文件名,去掉路径信息后,发给服务器 */
  119.  
    for(i= 0;i<= strlen(fileName);i++)
  120.  
    {
  121.  
    if(fileName[i]== ''/'')
  122.  
    {
  123.  
    j= 0;
  124.  
    continue;
  125.  
    }
  126.  
    else {sendFN[j]=fileName[i];++j;}
  127.  
    }
  128.  
    len = SSL_write(ssl, sendFN, strlen(sendFN));
  129.  
    if (len < 0)
  130.  
    printf( "''%s''message Send failure !Error code is %d,Error messages are ''%s''\n", buffer, errno, strerror(errno));
  131.  
     
  132.  
    /* 循环发送文件内容到服务器 */
  133.  
    bzero(buffer, MAXBUF + 1);
  134.  
    while((size=read(fd,buffer, 1024)))
  135.  
    {
  136.  
    if(size< 0)
  137.  
    {
  138.  
    perror( "read:");
  139.  
    exit( 1);
  140.  
    }
  141.  
    else
  142.  
    {
  143.  
    len = SSL_write(ssl, buffer, size);
  144.  
    if (len < 0)
  145.  
    printf( "''%s''message Send failure !Error code is %d,Error messages are ''%s''\n", buffer, errno, strerror(errno));
  146.  
    }
  147.  
    bzero(buffer, MAXBUF + 1);
  148.  
    }
  149.  
    printf( "Send complete !\n");
  150.  
     
  151.  
    /* 关闭连接 */
  152.  
    close(fd);
  153.  
    SSL_shutdown(ssl);
  154.  
    SSL_free(ssl);
  155.  
    close(sockfd);
  156.  
    SSL_CTX_free(ctx);
  157.  
    return 0;
  158.  
    }
 
服务端代码如下:
  1.  
    /*File: server_ssl.c
  2.  
    *Auth:sjin
  3.  
    *Date:2014-03-11
  4.  
    *
  5.  
    */
  6.  
    #include <stdio.h>
  7.  
    #include <stdlib.h>
  8.  
    #include <errno.h>
  9.  
    #include <string.h>
  10.  
    #include <sys/types.h>
  11.  
    #include <netinet/in.h>
  12.  
    #include <sys/socket.h>
  13.  
    #include <sys/wait.h>
  14.  
    #include <unistd.h>
  15.  
    #include <arpa/inet.h>
  16.  
    #include <sys/types.h>
  17.  
    #include <sys/stat.h>
  18.  
    #include <fcntl.h>
  19.  
    #include <openssl/ssl.h>
  20.  
    #include <openssl/err.h>
  21.  
     
  22.  
    #define MAXBUF 1024
  23.  
     
  24.  
    int main(int argc, char **argv)
  25.  
    {
  26.  
    int sockfd, new_fd, fd;
  27.  
    socklen_t len;
  28.  
    struct sockaddr_in my_addr, their_addr;
  29.  
    unsigned int myport, lisnum;
  30.  
    char buf[MAXBUF + 1];
  31.  
    char new_fileName[ 50]= "/newfile/";
  32.  
    SSL_CTX *ctx;
  33.  
    mode_t mode;
  34.  
    char pwd[ 100];
  35.  
    char* temp;
  36.  
     
  37.  
    /* 在根目录下创建一个 newfile 文件夹 */
  38.  
    mkdir( "/newfile",mode);
  39.  
     
  40.  
    if (argv[ 1])
  41.  
    myport = atoi(argv[ 1]);
  42.  
    else
  43.  
    {
  44.  
    myport = 7838;
  45.  
    argv[ 2]=argv[ 3]= NULL;
  46.  
    }
  47.  
     
  48.  
    if (argv[ 2])
  49.  
    lisnum = atoi(argv[ 2]);
  50.  
    else
  51.  
    {
  52.  
    lisnum = 2;
  53.  
    argv[ 3]= NULL;
  54.  
    }
  55.  
     
  56.  
    /* SSL 库初始化 */
  57.  
    SSL_library_init();
  58.  
    /* 载入所有 SSL 算法 */
  59.  
    OpenSSL_add_all_algorithms();
  60.  
    /* 载入所有 SSL 错误消息 */
  61.  
    SSL_load_error_strings();
  62.  
    /* 以 SSL V2 和 V3 标准兼容方式产生一个 SSL_CTX ,即 SSL Content Text */
  63.  
    ctx = SSL_CTX_new(SSLv23_server_method());
  64.  
    /* 也可以用 SSLv2_server_method () 或 SSLv3_server_method () 单独表示 V2 或 V3 标准 */
  65.  
    if (ctx == NULL)
  66.  
    {
  67.  
    ERR_print_errors_fp( stdout);
  68.  
    exit( 1);
  69.  
    }
  70.  
    /* 载入用户的数字证书, 此证书用来发送给客户端。 证书里包含有公钥 */
  71.  
    getcwd(pwd, 100);
  72.  
    if( strlen(pwd)== 1)
  73.  
    pwd[ 0]= ''\0'';
  74.  
    if (SSL_CTX_use_certificate_file(ctx, temp= strcat(pwd, "/cacert.pem"), SSL_FILETYPE_PEM) <= 0)
  75.  
    {
  76.  
    ERR_print_errors_fp( stdout);
  77.  
    exit( 1);
  78.  
    }
  79.  
    /* 载入用户私钥 */
  80.  
    getcwd(pwd, 100);
  81.  
    if( strlen(pwd)== 1)
  82.  
    pwd[ 0]= ''\0'';
  83.  
    if (SSL_CTX_use_PrivateKey_file(ctx, temp= strcat(pwd, "/privkey.pem"), SSL_FILETYPE_PEM) <= 0)
  84.  
    {
  85.  
    ERR_print_errors_fp( stdout);
  86.  
    exit( 1);
  87.  
    }
  88.  
    /* 检查用户私钥是否正确 */
  89.  
    if (!SSL_CTX_check_private_key(ctx))
  90.  
    {
  91.  
    ERR_print_errors_fp( stdout);
  92.  
    exit( 1);
  93.  
    }
  94.  
     
  95.  
    /* 开启一个 socket 监听 */
  96.  
    if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1)
  97.  
    {
  98.  
    perror( "socket");
  99.  
    exit( 1);
  100.  
    }
  101.  
    else
  102.  
    printf( "socket created\n");
  103.  
     
  104.  
    bzero(&my_addr, sizeof(my_addr));
  105.  
    my_addr.sin_family = PF_INET;
  106.  
    my_addr.sin_port = htons(myport);
  107.  
    if (argv[ 3])
  108.  
    my_addr.sin_addr.s_addr = inet_addr(argv[ 3]);
  109.  
    else
  110.  
    my_addr.sin_addr.s_addr = INADDR_ANY;
  111.  
     
  112.  
    if (bind(sockfd, (struct sockaddr *) &my_addr, sizeof(struct sockaddr)) == -1)
  113.  
    {
  114.  
    perror( "bind");
  115.  
    exit( 1);
  116.  
    }
  117.  
    else
  118.  
    printf( "binded\n");
  119.  
     
  120.  
    if (listen(sockfd, lisnum) == -1)
  121.  
    {
  122.  
    perror( "listen");
  123.  
    exit( 1);
  124.  
    }
  125.  
    else
  126.  
    printf( "begin listen\n");
  127.  
     
  128.  
    while ( 1)
  129.  
    {
  130.  
    SSL *ssl;
  131.  
    len = sizeof(struct sockaddr);
  132.  
    /* 等待客户端连上来 */
  133.  
    if ((new_fd = accept(sockfd, (struct sockaddr *) &their_addr, &len)) == -1)
  134.  
    {
  135.  
    perror( "accept");
  136.  
    exit(errno);
  137.  
    }
  138.  
    else
  139.  
    printf( "server: got connection from %s, port %d, socket %d\n", inet_ntoa(their_addr.sin_addr), ntohs(their_addr.sin_port), new_fd);
  140.  
     
  141.  
    /* 基于 ctx 产生一个新的 SSL */
  142.  
    ssl = SSL_new(ctx);
  143.  
    /* 将连接用户的 socket 加入到 SSL */
  144.  
    SSL_set_fd(ssl, new_fd);
  145.  
    /* 建立 SSL 连接 */
  146.  
    if (SSL_accept(ssl) == -1)
  147.  
    {
  148.  
    perror( "accept");
  149.  
    close(new_fd);
  150.  
    break;
  151.  
    }
  152.  
     
  153.  
    /* 接受客户端所传文件的文件名并在特定目录创建空文件 */
  154.  
    bzero(buf, MAXBUF + 1);
  155.  
    bzero(new_fileName+ 9, 42);
  156.  
    len = SSL_read(ssl, buf, MAXBUF);
  157.  
    if(len == 0)
  158.  
    printf( "Receive Complete !\n");
  159.  
    else if(len < 0)
  160.  
    printf( "Failure to receive message ! Error code is %d,Error messages are ''%s''\n", errno, strerror(errno));
  161.  
    if((fd = open( strcat(new_fileName,buf),O_CREAT | O_TRUNC | O_RDWR, 0666))< 0)
  162.  
    {
  163.  
    perror( "open:");
  164.  
    exit( 1);
  165.  
    }
  166.  
     
  167.  
    /* 接收客户端的数据并写入文件 */
  168.  
    while( 1)
  169.  
    {
  170.  
    bzero(buf, MAXBUF + 1);
  171.  
    len = SSL_read(ssl, buf, MAXBUF);
  172.  
    if(len == 0)
  173.  
    {
  174.  
    printf( "Receive Complete !\n");
  175.  
    break;
  176.  
    }
  177.  
    else if(len < 0)
  178.  
    {
  179.  
    printf( "Failure to receive message ! Error code is %d,Error messages are ''%s''\n", errno, strerror(errno));
  180.  
    exit( 1);
  181.  
    }
  182.  
    if(write(fd,buf,len)< 0)
  183.  
    {
  184.  
    perror( "write:");
  185.  
    exit( 1);
  186.  
    }
  187.  
    }
  188.  
     
  189.  
    /* 关闭文件 */
  190.  
    close(fd);
  191.  
    /* 关闭 SSL 连接 */
  192.  
    SSL_shutdown(ssl);
  193.  
    /* 释放 SSL */
  194.  
    SSL_free(ssl);
  195.  
    /* 关闭 socket */
  196.  
    close(new_fd);
  197.  
    }
  198.  
     
  199.  
    /* 关闭监听的 socket */
  200.  
    close(sockfd);
  201.  
    /* 释放 CTX */
  202.  
    SSL_CTX_free(ctx);
  203.  
    return 0;
  204.  
    }
 gcc -o c client_ssl.c -Wall -lssl -ldl -lcurses -lcrypto -g
gcc -o s server_ssl.c -Wall -lssl -ldl -lcurses -lcrypto -g

以下是 Openssl 双向认证客户端代码
openssl 是一个功能丰富且自包含的开源安全工具箱。它提供的主要功能有:SSL 协议实现 (包括 SSLv2、SSLv3 和 TLSv1)、大量软算法 (对称 / 非对称 / 摘要)、大数运算、非对称算法密钥生成、ASN.1 编解码库、证书请求 (PKCS10) 编解码、数字证书编解码、CRL 编解码、OCSP 协议、数字证书验证、PKCS7 标准实现和 PKCS12 个人数字证书格式实现等功能。
本文主要介绍 openssl 进行客户端 - 服务器双向验证的通信,客户端应该如何设置。包括了如何使用 openssl 指令生成客户端 - 服务端的证书和密钥,以及使用 openssl 自带 server 端来实现简单的 ssl 双向认证,client 端代码中也做了相应的标注和说明,提供编译的 Makefile. 希望对开始学习如何使用 openssl 进行安全连接的朋友有益。


1. 首先介绍如何生成客户和服务端证书 (PEM) 及密钥。
在 linux 环境下下载并安装 openssl 开发包后,通过 openssl 命令来建立一个 SSL 测试环境。
1) 建立自己的 CA
 在 openssl 安装目录的 misc 目录下,运行脚本:./CA.sh -newca,出现提示符时,直接回车。  运行完毕后会生成一个 demonCA 的目录,里面包含了 ca 证书及其私钥。
2) 生成客户端和服务端证书申请:
 openssl  req  -newkey  rsa:1024  -out  req1.pem  -keyout  sslclientkey.pem
openssl  req  -newkey  rsa:1024  -out  req2.pem  -keyout  sslserverkey.pem
3) 签发客户端和服务端证书
openssl  ca  -in  req1.pem  -out  sslclientcert.pem
openssl  ca  -in  req2.pem  -out  sslservercert.pem
4) 运行 ssl 服务端:
openssl s_server -cert sslservercert.pem -key sslserverkey.pem -CAfile demoCA/cacert.pem -ssl3 
当然我们也可以使用 openssl 自带的客户端:
openssl s_client -ssl3 -CAfile demoCA/cacert.pem
但这里我们为了介绍 client 端的设置过程,还是从一下代码来看看如何书写吧。

 

  1.  
    #include <openssl/ssl.h>
  2.  
    #include <openssl/crypto.h>
  3.  
    #include <openssl/err.h>
  4.  
    #include <openssl/bio.h>
  5.  
    #include <openssl/pkcs12.h>
  6.  
     
  7.  
    #include <unistd.h>
  8.  
    #include <stdio.h>
  9.  
    #include <string.h>
  10.  
    #include <stdlib.h>
  11.  
    #include <errno.h>
  12.  
    #include <sys/socket.h>
  13.  
    #include <sys/types.h>
  14.  
    #include <netinet/in.h>
  15.  
    #include <arpa/inet.h>
  16.  
     
  17.  
    #define IP "172.22.14.157"
  18.  
    #define PORT 4433
  19.  
    #define CERT_PATH "./sslclientcert.pem"
  20.  
    #define KEY_PATH "./sslclientkey.pem"
  21.  
    #define CAFILE "./demoCA/cacert.pem"
  22.  
    static SSL_CTX *g_sslctx = NULL;
  23.  
     
  24.  
     
  25.  
    int connect_to_server(int fd ,char* ip,int port){
  26.  
    struct sockaddr_in svr;
  27.  
    memset(&svr,0,sizeof(svr));
  28.  
    svr.sin_family = AF_INET;
  29.  
    svr.sin_port = htons(port);
  30.  
    if(inet_pton(AF_INET,ip,&svr.sin_addr) <= 0){
  31.  
    printf("invalid ip address!\n");
  32.  
    return -1;
  33.  
    }
  34.  
    if(connect(fd,(struct sockaddr *)&svr,sizeof(svr))){
  35.  
    printf("connect error : %s\n",strerror(errno));
  36.  
    return -1;
  37.  
    }
  38.  
     
  39.  
    return 0;
  40.  
    }
  41.  
     
  42.  
    // 客户端证书内容输出
  43.  
    void print_client_cert(char* path)
  44.  
    {
  45.  
    X509 *cert =NULL;
  46.  
    FILE *fp = NULL;
  47.  
    fp = fopen(path,"rb");
  48.  
    // 从证书文件中读取证书到 x509 结构中,passwd 1111, 此为生成证书时设置的
  49.  
    cert = PEM_read_X509(fp, NULL, NULL, "1111");
  50.  
    X509_NAME *name=NULL;
  51.  
    char buf[8192]={0};
  52.  
    BIO *bio_cert = NULL;
  53.  
    // 证书持有者信息
  54.  
    name = X509_get_subject_name(cert);
  55.  
    X509_NAME_oneline(name,buf,8191);
  56.  
    printf("ClientSubjectName:%s\n",buf);
  57.  
    memset(buf,0,sizeof(buf));
  58.  
    bio_cert = BIO_new(BIO_s_mem());
  59.  
    PEM_write_bio_X509(bio_cert, cert);
  60.  
    // 证书内容
  61.  
    BIO_read( bio_cert, buf, 8191);
  62.  
    printf("CLIENT CERT:\n%s\n",buf);
  63.  
    if(bio_cert)BIO_free(bio_cert);
  64.  
    fclose(fp);
  65.  
    if(cert) X509_free(cert);
  66.  
    }
  67.  
    // 在 SSL 握手时,验证服务端证书时会被调用,res 返回值为 1 则表示验证成功,否则为失败
  68.  
    static int verify_cb(int res, X509_STORE_CTX *xs)
  69.  
    {
  70.  
    printf("SSL VERIFY RESULT :%d\n",res);
  71.  
    switch (xs->error)
  72.  
    {
  73.  
    case X509_V_ERR_UNABLE_TO_GET_CRL:
  74.  
    printf(" NOT GET CRL!\n");
  75.  
    return 1;
  76.  
    default :
  77.  
    break;
  78.  
    }
  79.  
    return res;
  80.  
    }
  81.  
     
  82.  
    int sslctx_init()
  83.  
    {
  84.  
    #if 0
  85.  
    BIO *bio = NULL;
  86.  
    X509 *cert = NULL;
  87.  
    STACK_OF(X509) *ca = NULL;
  88.  
    EVP_PKEY *pkey =NULL;
  89.  
    PKCS12* p12 = NULL;
  90.  
    X509_STORE *store =NULL;
  91.  
    int error_code =0;
  92.  
    #endif
  93.  
     
  94.  
    int ret =0;
  95.  
    print_client_cert(CERT_PATH);
  96.  
    //registers the libssl error strings
  97.  
    SSL_load_error_strings();
  98.  
     
  99.  
    //registers the available SSL/TLS ciphers and digests
  100.  
    SSL_library_init();
  101.  
     
  102.  
    //creates a new SSL_CTX object as framework to establish TLS/SSL
  103.  
    g_sslctx = SSL_CTX_new(SSLv23_client_method());
  104.  
    if(g_sslctx == NULL){
  105.  
    ret = -1;
  106.  
    goto end;
  107.  
    }
  108.  
     
  109.  
    //passwd is supplied to protect the private key,when you want to read key
  110.  
    SSL_CTX_set_default_passwd_cb_userdata(g_sslctx,"1111");
  111.  
     
  112.  
    //set cipher ,when handshake client will send the cipher list to server
  113.  
    SSL_CTX_set_cipher_list(g_sslctx,"HIGH:MEDIA:LOW:!DH");
  114.  
    //SSL_CTX_set_cipher_list(g_sslctx,"AES128-SHA");
  115.  
     
  116.  
    //set verify ,when recive the server certificate and verify it
  117.  
    //and verify_cb function will deal the result of verification
  118.  
    SSL_CTX_set_verify(g_sslctx, SSL_VERIFY_PEER, verify_cb);
  119.  
     
  120.  
    //sets the maximum depth for the certificate chain verification that shall
  121.  
    //be allowed for ctx
  122.  
    SSL_CTX_set_verify_depth(g_sslctx, 10);
  123.  
     
  124.  
    //load the certificate for verify server certificate, CA file usually load
  125.  
    SSL_CTX_load_verify_locations(g_sslctx,CAFILE, NULL);
  126.  
     
  127.  
    //load user certificate,this cert will be send to server for server verify
  128.  
    if(SSL_CTX_use_certificate_file(g_sslctx,CERT_PATH,SSL_FILETYPE_PEM) <= 0){
  129.  
    printf("certificate file error!\n");
  130.  
    ret = -1;
  131.  
    goto end;
  132.  
    }
  133.  
    //load user private key
  134.  
    if(SSL_CTX_use_PrivateKey_file(g_sslctx,KEY_PATH,SSL_FILETYPE_PEM) <= 0){
  135.  
    printf("privatekey file error!\n");
  136.  
    ret = -1;
  137.  
    goto end;
  138.  
    }
  139.  
    if(!SSL_CTX_check_private_key(g_sslctx)){
  140.  
    printf("Check private key failed!\n");
  141.  
    ret = -1;
  142.  
    goto end;
  143.  
    }
  144.  
     
  145.  
    end:
  146.  
    return ret;
  147.  
    }
  148.  
     
  149.  
    void sslctx_release()
  150.  
    {
  151.  
    EVP_cleanup();
  152.  
    if(g_sslctx){
  153.  
    SSL_CTX_free(g_sslctx);
  154.  
    }
  155.  
    g_sslctx= NULL;
  156.  
    }
  157.  
    // 打印服务端证书相关内容
  158.  
    void print_peer_certificate(SSL *ssl)
  159.  
    {
  160.  
    X509* cert= NULL;
  161.  
    X509_NAME *name=NULL;
  162.  
    char buf[8192]={0};
  163.  
    BIO *bio_cert = NULL;
  164.  
    // 获取 server 端证书
  165.  
    cert = SSL_get_peer_certificate(ssl);
  166.  
    // 获取证书拥有者信息
  167.  
    name = X509_get_subject_name(cert);
  168.  
    X509_NAME_oneline(name,buf,8191);
  169.  
    printf("ServerSubjectName:%s\n",buf);
  170.  
    memset(buf,0,sizeof(buf));
  171.  
    bio_cert = BIO_new(BIO_s_mem());
  172.  
    PEM_write_bio_X509(bio_cert, cert);
  173.  
    BIO_read( bio_cert, buf, 8191);
  174.  
    //server 证书内容
  175.  
    printf("SERVER CERT:\n%s\n",buf);
  176.  
    if(bio_cert)BIO_free(bio_cert);
  177.  
    if(cert)X509_free(cert);
  178.  
    }
  179.  
     
  180.  
    int main(int argc, char** argv){
  181.  
    int fd = -1 ,ret = 0;
  182.  
    SSL *ssl = NULL;
  183.  
    char buf[1024] ={0};
  184.  
    // 初始化 SSL
  185.  
    if(sslctx_init()){
  186.  
    printf("sslctx init failed!\n");
  187.  
    goto out;
  188.  
    }
  189.  
    // 客户端 socket 建立 tcp 连接
  190.  
    fd = socket(AF_INET,SOCK_STREAM,0);
  191.  
    if(fd < 0){
  192.  
    printf("socket error:%s\n",strerror(errno));
  193.  
    goto out;
  194.  
    }
  195.  
     
  196.  
    if(connect_to_server(fd ,IP,PORT)){
  197.  
    printf("can''t connect to server:%s:%d\n",IP,PORT);
  198.  
    goto out;
  199.  
    }
  200.  
    ssl = SSL_new(g_sslctx);
  201.  
    if(!ssl){
  202.  
    printf("can''t get ssl from ctx!\n");
  203.  
    goto out;
  204.  
    }
  205.  
    SSL_set_fd(ssl,fd);
  206.  
    // 建立与服务端 SSL 连接
  207.  
    ret = SSL_connect(ssl);
  208.  
    if(ret != 1){
  209.  
    int err = ERR_get_error();
  210.  
    printf("Connect error code: %d ,string: %s\n",err,ERR_error_string(err,NULL));
  211.  
    goto out;
  212.  
    }
  213.  
    // 输入服务端证书内容
  214.  
    print_peer_certificate(ssl);
  215.  
     
  216.  
    //SSL_write(ssl,"sslclient test!",strlen("sslclient test!"));
  217.  
    //SSL_read(ssl,buf,1024);
  218.  
    // 关闭 SSL 连接
  219.  
    SSL_shutdown(ssl);
  220.  
     
  221.  
     
  222.  
    out:
  223.  
    if(fd >0)close(fd);
  224.  
    if(ssl != NULL){
  225.  
    SSL_free(ssl);
  226.  
    ssl = NULL;
  227.  
    }
  228.  
    if(g_sslctx != NULL) sslctx_release();
  229.  
    return 0;
  230.  
    }


参考资料:

 

http://www.169it.com/article/3215130236.html

HttpClient4实现SSL双向认证的客户端(一)

HttpClient4实现SSL双向认证的客户端(一)

HttpClient4实现SSL双向认证的客户端

服务器端使用netty实现的http服务器端,只能处理get和post请求。下面是具体的代码:

HttpDemoServer.java

package https;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * A HTTP server showing how to use the HTTP multipart package for file uploads.
 */
public class HttpDemoServer {

    private final int port;
    public static boolean isSSL;

    public HttpDemoServer(int port) {
        this.port = port;
    }

    public void run() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .childHandler(new HttpDemoServerInitializer());

            Channel ch = b.bind(port).sync().channel();
            ch.closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        int port = 8888;
        isSSL = true;
        new HttpDemoServer(port).run();
    }
}

 

HttpDemoServerInitializer.java

package https;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpContentCompressor;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.ssl.SslHandler;

import javax.net.ssl.SSLEngine;

public class HttpDemoServerInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    public void initChannel(SocketChannel ch) throws Exception {
        // Create a default pipeline implementation.
        ChannelPipeline pipeline = ch.pipeline();

        if (HttpDemoServer.isSSL) {
            SSLEngine engine = SecureChatSslContextFactory.getServerContext().createSSLEngine();
            engine.setNeedClientAuth(true); //ssl双向认证
            engine.setUseClientMode(false);
            engine.setWantClientAuth(true);
            engine.setEnabledProtocols(new String[]{"SSLv3"});
            pipeline.addLast("ssl", new SslHandler(engine));
        }

        /**
         * http服务器端对request解码
         */
        pipeline.addLast("decoder", new HttpRequestDecoder());
        /**
         * http服务器端对response编码
         */
        pipeline.addLast("encoder", new HttpResponseEncoder());

        pipeline.addLast("aggregator", new HttpObjectAggregator(1048576));
        /**
         * 压缩
         * Compresses an HttpMessage and an HttpContent in gzip or deflate encoding
         * while respecting the "Accept-Encoding" header.
         * If there is no matching encoding, no compression is done.
         */
        pipeline.addLast("deflater", new HttpContentCompressor());

        pipeline.addLast("handler", new HttpDemoServerHandler());
    }
}

 

HttpDemoServerHandler.java

package https;

import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.multipart.*;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.EndOfDataDecoderException;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.ErrorDataDecoderException;
import io.netty.handler.codec.http.multipart.InterfaceHttpData.HttpDataType;
import io.netty.handler.ssl.SslHandler;
import io.netty.util.CharsetUtil;

import java.io.IOException;
import java.net.URI;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

import static io.netty.buffer.Unpooled.copiedBuffer;
import static io.netty.handler.codec.http.HttpHeaders.Names.*;

public class HttpDemoServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    private static final Logger logger = Logger.getLogger(HttpDemoServerHandler.class.getName());

    private DefaultFullHttpRequest fullHttpRequest;

    private boolean readingChunks;

    private final StringBuilder responseContent = new StringBuilder();

    private static final HttpDataFactory factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE); //Disk

    private HttpPostRequestDecoder decoder;

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        if (decoder != null) {
            decoder.cleanFiles();
        }
    }

    public void messageReceived(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        fullHttpRequest = (DefaultFullHttpRequest) msg;

        if (HttpDemoServer.isSSL) {
            System.out.println("Your session is protected by " +
                    ctx.pipeline().get(SslHandler.class).engine().getSession().getCipherSuite() +
                    " cipher suite.\n");
        }
        /**
         * 在服务器端打印请求信息
         */
        System.out.println("VERSION: " + fullHttpRequest.getProtocolVersion().text() + "\r\n");
        System.out.println("REQUEST_URI: " + fullHttpRequest.getUri() + "\r\n\r\n");
        System.out.println("\r\n\r\n");
        for (Entry<String, String> entry : fullHttpRequest.headers()) {
            System.out.println("HEADER: " + entry.getKey() + ''='' + entry.getValue() + "\r\n");
        }

        /**
         * 服务器端返回信息
         */
        responseContent.setLength(0);
        responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n");
        responseContent.append("===================================\r\n");

        responseContent.append("VERSION: " + fullHttpRequest.getProtocolVersion().text() + "\r\n");
        responseContent.append("REQUEST_URI: " + fullHttpRequest.getUri() + "\r\n\r\n");
        responseContent.append("\r\n\r\n");
        for (Entry<String, String> entry : fullHttpRequest.headers()) {
            responseContent.append("HEADER: " + entry.getKey() + ''='' + entry.getValue() + "\r\n");
        }
        responseContent.append("\r\n\r\n");
        Set<Cookie> cookies;
        String value = fullHttpRequest.headers().get(COOKIE);
        if (value == null) {
            cookies = Collections.emptySet();
        } else {
            cookies = CookieDecoder.decode(value);
        }
        for (Cookie cookie : cookies) {
            responseContent.append("COOKIE: " + cookie.toString() + "\r\n");
        }
        responseContent.append("\r\n\r\n");

        if (fullHttpRequest.getMethod().equals(HttpMethod.GET)) {
            //get请求
            QueryStringDecoder decoderQuery = new QueryStringDecoder(fullHttpRequest.getUri());
            Map<String, List<String>> uriAttributes = decoderQuery.parameters();
            for (Entry<String, List<String>> attr : uriAttributes.entrySet()) {
                for (String attrVal : attr.getValue()) {
                    responseContent.append("URI: " + attr.getKey() + ''='' + attrVal + "\r\n");
                }
            }
            responseContent.append("\r\n\r\n");

            responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n");
            writeResponse(ctx.channel());
            return;
        } else if (fullHttpRequest.getMethod().equals(HttpMethod.POST)) {
            //post请求
            decoder = new HttpPostRequestDecoder(factory, fullHttpRequest);
            readingChunks = HttpHeaders.isTransferEncodingChunked(fullHttpRequest);
            responseContent.append("Is Chunked: " + readingChunks + "\r\n");
            responseContent.append("IsMultipart: " + decoder.isMultipart() + "\r\n");

            try {
                while (decoder.hasNext()) {
                    InterfaceHttpData data = decoder.next();
                    if (data != null) {
                        try {
                            writeHttpData(data);
                        } finally {
                            data.release();
                        }
                    }
                }
            } catch (EndOfDataDecoderException e1) {
                responseContent.append("\r\n\r\nEND OF POST CONTENT\r\n\r\n");
            }
            writeResponse(ctx.channel());
            return;
        } else {
            System.out.println("discard.......");
            return;
        }
    }

    private void reset() {
        fullHttpRequest = null;
        // destroy the decoder to release all resources
        decoder.destroy();
        decoder = null;
    }

    private void writeHttpData(InterfaceHttpData data) {

        /**
         * HttpDataType有三种类型
         * Attribute, FileUpload, InternalAttribute
         */
        if (data.getHttpDataType() == HttpDataType.Attribute) {
            Attribute attribute = (Attribute) data;
            String value;
            try {
                value = attribute.getValue();
            } catch (IOException e1) {
                e1.printStackTrace();
                responseContent.append("\r\nBODY Attribute: " + attribute.getHttpDataType().name() + ":"
                        + attribute.getName() + " Error while reading value: " + e1.getMessage() + "\r\n");
                return;
            }
            if (value.length() > 100) {
                responseContent.append("\r\nBODY Attribute: " + attribute.getHttpDataType().name() + ":"
                        + attribute.getName() + " data too long\r\n");
            } else {
                responseContent.append("\r\nBODY Attribute: " + attribute.getHttpDataType().name() + ":"
                        + attribute.toString() + "\r\n");
            }
        }
    }


    /**
     * http返回响应数据
     *
     * @param channel
     */
    private void writeResponse(Channel channel) {
        // Convert the response content to a ChannelBuffer.
        ByteBuf buf = copiedBuffer(responseContent.toString(), CharsetUtil.UTF_8);
        responseContent.setLength(0);

        // Decide whether to close the connection or not.
        boolean close = fullHttpRequest.headers().contains(CONNECTION, HttpHeaders.Values.CLOSE, true)
                || fullHttpRequest.getProtocolVersion().equals(HttpVersion.HTTP_1_0)
                && !fullHttpRequest.headers().contains(CONNECTION, HttpHeaders.Values.KEEP_ALIVE, true);

        // Build the response object.
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);
        response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");

        if (!close) {
            // There''s no need to add ''Content-Length'' header
            // if this is the last response.
            response.headers().set(CONTENT_LENGTH, buf.readableBytes());
        }

        Set<Cookie> cookies;
        String value = fullHttpRequest.headers().get(COOKIE);
        if (value == null) {
            cookies = Collections.emptySet();
        } else {
            cookies = CookieDecoder.decode(value);
        }
        if (!cookies.isEmpty()) {
            // Reset the cookies if necessary.
            for (Cookie cookie : cookies) {
                response.headers().add(SET_COOKIE, ServerCookieEncoder.encode(cookie));
            }
        }
        // Write the response.
        ChannelFuture future = channel.writeAndFlush(response);
        // Close the connection after the write operation is done if necessary.
        if (close) {
            future.addListener(ChannelFutureListener.CLOSE);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.log(Level.WARNING, responseContent.toString(), cause);
        ctx.channel().close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        messageReceived(ctx, msg);
    }
}

 

SecureChatSslContextFactory.java

这个类是用来进行设置ssl通信的类。。

package https;

import javax.net.ssl.*;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public final class SecureChatSslContextFactory {

    private static final String PROTOCOL = "SSL";
    private static final SSLContext SERVER_CONTEXT;
//    private static final SSLContext CLIENT_CONTEXT;


//    private static String CLIENT_KEY_STORE = "E:\\https\\client.keystore";
//    private static String CLIENT_TRUST_KEY_STORE = "E:\\https\\client.truststore";
//    private static String CLIENT_KEY_STORE_PASSWORD = "123456";
//    private static String CLIENT_TRUST_KEY_STORE_PASSWORD = "123456";


    private static String SERVER_KEY_STORE = "E:\\https\\server.keystore";
    private static String SERVER_TRUST_KEY_STORE = "E:\\https\\server.truststore";
    private static String SERVER_KEY_STORE_PASSWORD = "123456";
    private static String SERVER_TRUST_KEY_STORE_PASSWORD = "123456";

    static {
        SSLContext serverContext;
//        SSLContext clientContext;
        try {
            KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
            ks.load(new FileInputStream(SERVER_KEY_STORE), SERVER_KEY_STORE_PASSWORD.toCharArray());
            KeyStore tks = KeyStore.getInstance(KeyStore.getDefaultType());
            tks.load(new FileInputStream(SERVER_TRUST_KEY_STORE), SERVER_TRUST_KEY_STORE_PASSWORD.toCharArray());

            // Set up key manager factory to use our key store
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            kmf.init(ks, SERVER_KEY_STORE_PASSWORD.toCharArray());
            tmf.init(tks);

            // Initialize the SSLContext to work with our key managers.
            serverContext = SSLContext.getInstance(PROTOCOL);
            serverContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        } catch (Exception e) {
            throw new Error("Failed to initialize the server-side SSLContext", e);
        }

//        try {
//            KeyStore ks2 = KeyStore.getInstance("JKS");
//            ks2.load(new FileInputStream(CLIENT_KEY_STORE), CLIENT_KEY_STORE_PASSWORD.toCharArray());
//
//            KeyStore tks2 = KeyStore.getInstance("JKS");
//            tks2.load(new FileInputStream(CLIENT_TRUST_KEY_STORE), CLIENT_TRUST_KEY_STORE_PASSWORD.toCharArray());
//            // Set up key manager factory to use our key store
//            KeyManagerFactory kmf2 = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
//            TrustManagerFactory tmf2 = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
//            kmf2.init(ks2, CLIENT_KEY_STORE_PASSWORD.toCharArray());
//            tmf2.init(tks2);
//            clientContext = SSLContext.getInstance(PROTOCOL);
//            clientContext.init(kmf2.getKeyManagers(), tmf2.getTrustManagers(), null);
//        } catch (Exception e) {
//            throw new Error("Failed to initialize the client-side SSLContext", e);
//        }

        SERVER_CONTEXT = serverContext;
//        CLIENT_CONTEXT = clientContext;
    }


    public static SSLContext getServerContext() {
        return SERVER_CONTEXT;
    }


//    public static SSLContext getClientContext() {
//        return CLIENT_CONTEXT;
//    }

    private SecureChatSslContextFactory() {
        // Unused
    }
}

 

好了以上就是服务器端程序。

在服务器端要配置服务器端使用的证书和信任库。

具体如何生成证书和密钥库,在这篇文章中有写到http://my.oschina.net/xinxingegeya/blog/266826

下篇文章就来看如何实现httpclient客户端进行双向认证的ssl通信过程。

=========================

http://my.oschina.net/xinxingegeya/blog/289264

=========================

HttpClient4实现SSL双向认证的客户端(二)

HttpClient4实现SSL双向认证的客户端(二)

在上篇文章中写到了如何实现服务端程序,主要是netty实现的。还有如何生成证书和密钥库。

这篇文章主要讲客户端如何实现:

 

httpclient实现连接池并进行ssl通信

HttpClientUtils2.java

package https;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.util.*;

/**
 * ssl通信的client
 */
public class HttpClientUtils2 {

    private static PoolingHttpClientConnectionManager secureConnectionManager;
    private static HttpClientBuilder secureHttpBulder = null;
    private static RequestConfig requestConfig = null;
    private static int MAXCONNECTION = 10;
    private static int DEFAULTMAXCONNECTION = 5;

    private static String CLIENT_KEY_STORE = "E:\\https\\client.keystore";
    private static String CLIENT_TRUST_KEY_STORE = "E:\\https\\client.truststore";
    private static String CLIENT_KEY_STORE_PASSWORD = "123456";
    private static String CLIENT_TRUST_KEY_STORE_PASSWORD = "123456";
    private static String CLIENT_KEY_PASS = "123456";

    /**
     * 进行安全通信的主机和端口
     */
    private static String HOST = "127.0.0.1";
    private static int PORT = 8888;

    static {
        //设置http的状态参数
        requestConfig = RequestConfig.custom()
                .setSocketTimeout(5000)
                .setConnectTimeout(5000)
                .setConnectionRequestTimeout(5000)
                .build();

        try {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            FileInputStream trustStoreInput = new FileInputStream(new File(CLIENT_TRUST_KEY_STORE));
            trustStore.load(trustStoreInput, CLIENT_TRUST_KEY_STORE_PASSWORD.toCharArray());
            KeyStore clientKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            FileInputStream clientKeyStoreInput = new FileInputStream(new File(CLIENT_KEY_STORE));
            clientKeyStore.load(clientKeyStoreInput, CLIENT_KEY_STORE_PASSWORD.toCharArray());

            SSLContext sslContext = SSLContexts.custom()
                    .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
                    .loadKeyMaterial(clientKeyStore, CLIENT_KEY_PASS.toCharArray())
                    .setSecureRandom(new SecureRandom())
                    .useSSL()
                    .build();


            ConnectionSocketFactory plainSocketFactory = new PlainConnectionSocketFactory();
            SSLConnectionSocketFactory sslSocketFactoy = new SSLConnectionSocketFactory(
                    sslContext, new String[]{"SSLv3"}, null,
                    SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

            Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", plainSocketFactory)
                    .register("https", sslSocketFactoy)
                    .build();

            secureConnectionManager = new PoolingHttpClientConnectionManager(r);
            HttpHost target = new HttpHost(HOST, PORT, "https");
            secureConnectionManager.setMaxTotal(MAXCONNECTION);
            //设置每个Route的连接最大数
            secureConnectionManager.setDefaultMaxPerRoute(DEFAULTMAXCONNECTION);
            //设置指定域的连接最大数
            secureConnectionManager.setMaxPerRoute(new HttpRoute(target), 20);
            secureHttpBulder = HttpClients.custom().setConnectionManager(secureConnectionManager);
        } catch (Exception e) {
            throw new Error("Failed to initialize the server-side SSLContext", e);
        }
    }

    public static CloseableHttpClient getSecureConnection() throws Exception {
        return secureHttpBulder.build();
    }


    public static HttpUriRequest getRequestMethod(Map<String, String> map, String url, String method) {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        Set<Map.Entry<String, String>> entrySet = map.entrySet();
        for (Map.Entry<String, String> e : entrySet) {
            String name = e.getKey();
            String value = e.getValue();
            NameValuePair pair = new BasicNameValuePair(name, value);
            params.add(pair);
        }
        HttpUriRequest reqMethod = null;
        if ("post".equals(method)) {
            reqMethod = RequestBuilder.post().setUri(url)
                    .addParameters(params.toArray(new BasicNameValuePair[params.size()]))
                    .setConfig(requestConfig).build();
        } else if ("get".equals(method)) {
            reqMethod = RequestBuilder.get().setUri(url)
                    .addParameters(params.toArray(new BasicNameValuePair[params.size()]))
                    .setConfig(requestConfig).build();
        }
        return reqMethod;
    }


    public static void main(String args[]) throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        map.put("account", "sdsdsd");
        map.put("password", "98765");

        HttpClient client = getSecureConnection(); //使用ssl通信
        HttpUriRequest post = getRequestMethod(map, "https://127.0.0.1:8888/", "post");
        HttpResponse response = client.execute(post);

        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();
            String message = EntityUtils.toString(entity, "utf-8");
            System.out.println(message);
        } else {
            System.out.println("请求失败");
        }
    }
}

上面的httpclient实现了连接池,并可以进行ssl双向认证的通信过程。其实也可以进行不加密的http通信。

运行结果:

服务器端

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Your session is protected by TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA cipher suite.

 

VERSION: HTTP/1.1

 

REQUEST_URI: /

 

HEADER: Content-Type=application/x-www-form-urlencoded; charset=ISO-8859-1

 

HEADER: Host=127.0.0.1:8888

 

HEADER: Connection=Keep-Alive

 

HEADER: User-Agent=Apache-HttpClient/4.3.3 (java 1.5)

 

HEADER: Accept-Encoding=gzip,deflate

 

HEADER: Content-Length=29

 

七月 10, 2014 11:55:07 上午 https.HttpDemoServerHandler exceptionCaught

警告: 

java.io.IOException: 远程主机强迫关闭了一个现有的连接。

有异常,这不是主要的,是因为没有关闭连接。

客户端

WELCOME TO THE WILD WILD WEB SERVER

===================================

VERSION: HTTP/1.1

REQUEST_URI: /

 

HEADER: Content-Type=application/x-www-form-urlencoded; charset=ISO-8859-1

HEADER: Host=127.0.0.1:8888

HEADER: Connection=Keep-Alive

HEADER: User-Agent=Apache-HttpClient/4.3.3 (java 1.5)

HEADER: Accept-Encoding=gzip,deflate

HEADER: Content-Length=29

 

Is Chunked: false

IsMultipart: false

 

BODY Attribute: Attribute:Mixed: password=98765

 

BODY Attribute: Attribute:Mixed: account=sdsdsd

 

END OF POST CONTENT

 

Process finished with exit code 0

 

httpclien客户端二

httpclient还有一种方式可以进行ssl通信。下面看这段代码:

ClientCustomSSL.java

package https;

import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * This example demonstrates how to create secure connections with a custom SSL
 * context.
 */
public class ClientCustomSSL {

    private static String CLIENT_KEY_STORE = "E:\\https\\client.keystore";
    private static String CLIENT_TRUST_KEY_STORE = "E:\\https\\client.truststore";
    private static String CLIENT_KEY_STORE_PASSWORD = "123456";
    private static String CLIENT_TRUST_KEY_STORE_PASSWORD = "123456";
    private static String CLIENT_KEY_PASS = "123456";


    public final static void main(String[] args) throws Exception {


        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        FileInputStream instream = new FileInputStream(new File(CLIENT_TRUST_KEY_STORE));
        try {
            trustStore.load(instream, CLIENT_TRUST_KEY_STORE_PASSWORD.toCharArray());
        } finally {
            instream.close();
        }

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        FileInputStream keyStoreInput = new FileInputStream(new File(CLIENT_KEY_STORE));
        try {
            keyStore.load(keyStoreInput, CLIENT_KEY_STORE_PASSWORD.toCharArray());
        } finally {
            keyStoreInput.close();
        }

        // Trust own CA and all self-signed certs
        SSLContext sslcontext = SSLContexts.custom()
                .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
                .loadKeyMaterial(keyStore, CLIENT_KEY_PASS.toCharArray())
                .build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext,
                new String[]{"SSLv3"},
                null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        CloseableHttpClient httpclient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .build();
        try {

            HttpPost httpPost = new HttpPost("https://127.0.0.1:8888/");

            System.out.println("executing request" + httpPost.getRequestLine());

            CloseableHttpResponse response = httpclient.execute(httpPost);
            try {
                HttpEntity entity = response.getEntity();

                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                if (entity != null) {
                    System.out.println("Response content length: " + entity.getContentLength());
                }
                EntityUtils.consume(entity);
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }
}

上面这段代码没有用到连接池,比较简单的实现了双向认证的ssl通信过程。

运行结果:

----------------------------------------

HTTP/1.1 200 OK

Response content length: -1

 

Process finished with exit code 0

==========END==========

IO :: Socket :: SSL似乎忽略了SSL_VERIFY_NONE

IO :: Socket :: SSL似乎忽略了SSL_VERIFY_NONE

这不是IO :: Socket :: SSL忽略public boolean isAlienSorted(String[] words,String order) { int[] index = new int[26]; for (int i = 0; i < order.length(); ++i) index[order.charAt(i) - 'a'] = i; search: for (int i = 0; i < words.length - 1; ++i) { String word1 = words[i]; String word2 = words[i+1]; // Find the first difference word1[k] != word2[k]. for (int k = 0; k < Math.min(word1.length(),word2.length()); ++k) { if (word1.charAt(k) != word2.charAt(k)) { // If they compare badly,it's not sorted. if (index[word1.charAt(k) - 'a'] > index[word2.charAt(k) - 'a']) return false; continue search; } } // If we didn't find a first difference,the // words are like ("app","apple"). if (word1.length() > word2.length()) return false; } return true; } ,而是LWP覆盖它。来自LWP::Protocol::https:

SSL_verify_mode

因此,您必须将sub _extra_sock_opts { my $self = shift; my %ssl_opts = %{$self->{ua}{ssl_opts} || {}}; if (delete $ssl_opts{verify_hostname}) { $ssl_opts{SSL_verify_mode} ||= 1; <<<<<<<<<<<<<<<<<<<< $ssl_opts{SSL_verifycn_scheme} = 'www'; } 设置为0才能实际禁用验证。另请参见票证LWP::Protocol::https discards 0 value for SSL_VERIFY_mode。

java keystore 实现ssl双向认证【客户端为php和java】

java keystore 实现ssl双向认证【客户端为php和java】

1.首先搭建server端环境:

准备工作:tomcat6、jdk7、openssl、javawebservice测试项目一个

2.搭建过程:

参考http://blog.csdn.net/chow__zh/article/details/8998499

 1.1生成服务端证书

立即学习“PHP免费学习笔记(深入)”;

点击下载“修复打印机驱动工具”;

keytool -genkey -v -alias tomcat -keyalg RSA -keystore D:/SSL/server/tomcat.keystore -dname "CN=127.0.0.1,OU=zlj,O=zlj,L=Peking,ST=Peking,C=CN" -validity 3650 -storepass zljzlj -keypass zljzlj

 

说明:
keytool 是JDK提供的证书生成工具,所有参数的用法参见keytool –help
-genkey 创建新证书
-v 详细信息
-alias tomcat 以”tomcat”作为该证书的别名。这里可以根据需要修改
-keyalg RSA 指定算法
-keystore D:/SSL/server/tomcat.keystore 保存路径及文件名
-dname "CN=127.0.0.1,OU=zlj,O=zlj,L=Peking,ST=Peking,C=CN" 证书发行者身份,这里的CN要与发布后的访问域名一致。但由于我们是自己发行的证书,如果在浏览器访问,仍然会有警告提示。
-validity 3650证书有效期,单位为天
-storepass zljzlj 证书的存取密码
-keypass zljzlj 证书的私钥
    1.2 生成客户端证书 
    执行命令:
keytool ‐genkey ‐v ‐alias client ‐keyalg RSA ‐storetype PKCS12 ‐keystore D:/SSL/client/client.p12 ‐dname "CN=client,OU=zlj,O=zlj,L=bj,ST=bj,C=CN" ‐validity 3650 ‐storepass client ‐keypass client
说明:
    参数说明同上。这里的-dname 证书发行者身份可以和前面不同,到目前为止,这2个证书可以没有任何关系。下面要做的工作才是建立2者之间的信任关系。
    1.3 导出客户端证书 
    执行命令:
keytool ‐export ‐alias client ‐keystore D:/SSL/client/client.p12 ‐storetype PKCS12 ‐storepass client ‐rfc ‐file D:/SSL/client/client.cer
说明:
-export 执行导出
-file 导出文件的文件路径
    1.4 把客户端证书加入服务端证书信任列表 
    执行命令:
keytool ‐import ‐alias client ‐v ‐file D:/SSL/client/client.cer ‐keystore D:/SSL/server/tomcat.keystore ‐storepass zljzlj
说明:
参数说明同前。这里提供的密码是服务端证书的存取密码。
    1.5 导出服务端证书 
    执行命令:
keytool -export -alias tomcat -keystore D:/SSL/server/tomcat.keystore -storepass zljzlj -rfc -file D:/SSL/server/tomcat.cer
说明:
把服务端证书导出。这里提供的密码也是服务端证书的密码。
    1.6 生成客户端信任列表 
    执行命令:
keytool -import -file D:/SSL/server/tomcat.cer -storepass zljzlj -keystore D:/SSL/client/client.truststore -alias tomcat –noprompt
说明:
让客户端信任服务端证书
2. 配置服务端为只允许HTTPS连接
    2.1 配置Tomcat 目录下的/conf/server.xml 
Xml代码  收藏代码
           maxThreads="150" scheme="https" secure="true" clientAuth="true"    
       sslProtocol="TLS" keystoreFile="D:/SSL/server/tomcat.keystore"    
       keystorePass="zljzlj" truststoreFile="D:/SSL/server/tomcat.keystore"    
       truststorePass="zljzlj" />   
说明:

在server.xml里面这段内容本来是被注释掉的,如果想使用https的默认端口443,请修改这里的port参数。其中的clientAuth="true" 指定了双向证书认证。

2.将client.p12导入浏览器个人证书项中。

此时输入https://127.0.0.1:8443/会出现选择证书,点确定会提示https页面不安全是否继续,点继续。到此服务端搭建完成。

3.java调用server端直接上代码:

package test;
import javax.xml.namespace.QName;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
/**
 * 
 * @author gshen
 *
 */
public class TestEcVoteNotice {
 public static void main(String [] args) throws Exception {  
   System.setProperty("javax.net.ssl.trustStorePassword","zljzlj");    
   System.setProperty("javax.net.ssl.keyStoreType","PKCS12") ;    
   System.setProperty("javax.net.ssl.keyStore","D:/SSL/client/client.p12") ;    
   System.setProperty("javax.net.ssl.keyStorePassword","client") ;          
       System.setProperty("javax.net.debug", "all");
       
     //wsdl地址
String endpoint = "https://192.168.1.146:8443/pro/ws/getInfoService?wsdl";
//http://jarfiles.pandaidea.com/ 搜索axis.jar并下载,Service类在axis.jar
Service service = new Service();
//http://jarfiles.pandaidea.com/ 搜索axis.jar并下载,Call类在axis.jar
Call call = null;
try {
call = (Call) service.createCall();
//设置Call的调用地址
call.setTargetEndpointAddress(new java.net.URL(endpoint));
//根据wsdl中 <wsdl:import location="https://192.168.10.24:8443/ShinService/HelloWorld?wsdl=HelloService.wsdl" 
//namespace="http://server.cxf.shinkong.cn/" /> ,
//<wsdl:operation name="findALL">
call.setOperationName(new QName("http://ws.task.xm.com/","sayHello"));  
//参数1对应服务端的@WebParam(name = "tableName") 没有设置名称为arg0
call.addParameter("id", XMLType.SOAP_STRING, javax.xml.rpc.ParameterMode.IN);
           //调用方法的返回值
           call.setReturnType(org.apache.axis.Constants.XSD_STRING);  
           //调用用Operation调用存储过程(以服务端的方法为准)
String res = (String) call.invoke(new Object[] {"1"});  //调用存储过程
System.out.println(res);
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
     }  
}
登录后复制

直接命令行运行或右键run as ,server端项目中我直接做了log打印,只要调用就会有打印。执行后

请看附件。

重点来了,接下来是php调用server,php的soapClient只识别DER、PEM或者ENG格式的证书,所以必须要把client.p12转换为php可识别的pem文件,这时用到了openssl,首先进入cmd命令行,敲入以下代码

Java代码

openssl pkcs12 -in D:\SSL\client\client.p12 -out D:\SSL\client\client-cer.pem -clcerts
登录后复制

如果提示openssl命令不识别则是你没安装openssl ,如果执行成功会提示你先输入client.p12的密码,输入后会让你输入导出的cer.pe的密码,输入后大功告成,client-cer.pem生成成功!。

这时上php代码:

Php代码

$params = array(&#39;id&#39; => &#39;2&#39;);  
  
    $local_cert = "./client-cer.pem";  
    set_time_limit(0);  
    try{  
        //ini_set("soap.wsdl_cache_enabled", "0"); // disabling WSDL cache  
        $wsdl=&#39;https://192.168.1.146:8443/pro/ws/getInfoService?wsdl&#39;;  
    //  echo file_get_contents($wsdl);  
          
        $soap=new SoapClient($wsdl,   
                    array(  
                        &#39;trace&#39;=>true,  
                        &#39;cache_wsdl&#39;=>WSDL_CACHE_NONE,   
                        &#39;soap_version&#39;   => SOAP_1_1,   
                        &#39;local_cert&#39; => $local_cert, //client证书信息  
                        &#39;passphrase&#39;=> &#39;client&#39;, //密码  
                       // &#39;allow_self_signed&#39;=> true  
                    )  
                );  
        $result=$soap->sayHello($params);  
        $result_json= json_encode($result);  
        $result= json_decode($result_json,true);  
        echo &#39;结果为:&#39; . json_decode($result[&#39;return&#39;],true);  
    }catch(Exception $e) {  
        $result[&#39;success&#39;] = &#39;0&#39;;  
        $result[&#39;msg&#39;] = &#39;请求超时&#39;;  
        echo $e->getMessage();  
    }  
    echo &#39;>>>>>>>>>>>&#39;;
登录后复制

 直接运行,也会出现附件中的结果,打完收工,憋了我整整三天时间,终于搞定了。

今天关于SSL 握手通信详解及 linux 下 c/c++ SSL Socket 代码举例 (另附 SSL 双向认证客户端代码)的分享就到这里,希望大家有所收获,若想了解更多关于HttpClient4实现SSL双向认证的客户端(一)、HttpClient4实现SSL双向认证的客户端(二)、IO :: Socket :: SSL似乎忽略了SSL_VERIFY_NONE、java keystore 实现ssl双向认证【客户端为php和java】等相关知识,可以在本站进行查询。

本文标签: