在本文中,我们将详细介绍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 双向认证客户端代码)
- 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 双向认证客户端代码)
摘自: https://blog.csdn.net/sjin_1314/article/details/21043613
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 的代码参考。
客户端代码如下:
-
/*File: client_ssl.c
-
*Auth:sjin
-
*Date:2014-03-11
-
*
-
*/
-
-
-
#include <stdio.h>
-
#include <string.h>
-
#include <errno.h>
-
#include <sys/socket.h>
-
#include <resolv.h>
-
#include <stdlib.h>
-
#include <netinet/in.h>
-
#include <arpa/inet.h>
-
#include <unistd.h>
-
#include <sys/types.h>
-
#include <sys/stat.h>
-
#include <fcntl.h>
-
#include <openssl/ssl.h>
-
#include <openssl/err.h>
-
-
#define MAXBUF 1024
-
-
void ShowCerts(SSL * ssl)
-
{
-
X509 *cert;
-
char *line;
-
-
cert = SSL_get_peer_certificate(ssl);
-
if (cert != NULL) {
-
printf( "Digital certificate information:\n");
-
line = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0);
-
printf( "Certificate: %s\n", line);
-
free(line);
-
line = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0);
-
printf( "Issuer: %s\n", line);
-
free(line);
-
X509_free(cert);
-
}
-
else
-
printf( "No certificate information!\n");
-
}
-
-
int main(int argc, char **argv)
-
{
-
int i,j,sockfd, len, fd, size;
-
char fileName[ 50],sendFN[ 20];
-
struct sockaddr_in dest;
-
char buffer[MAXBUF + 1];
-
SSL_CTX *ctx;
-
SSL *ssl;
-
-
if (argc != 3)
-
{
-
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);
-
}
-
-
/* SSL 库初始化 */
-
SSL_library_init();
-
OpenSSL_add_all_algorithms();
-
SSL_load_error_strings();
-
ctx = SSL_CTX_new(SSLv23_client_method());
-
if (ctx == NULL)
-
{
-
ERR_print_errors_fp( stdout);
-
exit( 1);
-
}
-
-
/* 创建一个 socket 用于 tcp 通信 */
-
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
-
{
-
perror( "Socket");
-
exit(errno);
-
}
-
printf( "socket created\n");
-
-
/* 初始化服务器端(对方)的地址和端口信息 */
-
bzero(&dest, sizeof(dest));
-
dest.sin_family = AF_INET;
-
dest.sin_port = htons(atoi(argv[ 2]));
-
if (inet_aton(argv[ 1], (struct in_addr *) &dest.sin_addr.s_addr) == 0)
-
{
-
perror(argv[ 1]);
-
exit(errno);
-
}
-
printf( "address created\n");
-
-
/* 连接服务器 */
-
if (connect(sockfd, (struct sockaddr *) &dest, sizeof(dest)) != 0)
-
{
-
perror( "Connect ");
-
exit(errno);
-
}
-
printf( "server connected\n\n");
-
-
/* 基于 ctx 产生一个新的 SSL */
-
ssl = SSL_new(ctx);
-
SSL_set_fd(ssl, sockfd);
-
/* 建立 SSL 连接 */
-
if (SSL_connect(ssl) == -1)
-
ERR_print_errors_fp( stderr);
-
else
-
{
-
printf( "Connected with %s encryption\n", SSL_get_cipher(ssl));
-
ShowCerts(ssl);
-
}
-
-
/* 接收用户输入的文件名,并打开文件 */
-
printf( "\nPlease input the filename of you want to load :\n>");
-
scanf( "%s",fileName);
-
if((fd = open(fileName,O_RDONLY, 0666))< 0)
-
{
-
perror( "open:");
-
exit( 1);
-
}
-
-
/* 将用户输入的文件名,去掉路径信息后,发给服务器 */
-
for(i= 0;i<= strlen(fileName);i++)
-
{
-
if(fileName[i]== ''/'')
-
{
-
j= 0;
-
continue;
-
}
-
else {sendFN[j]=fileName[i];++j;}
-
}
-
len = SSL_write(ssl, sendFN, strlen(sendFN));
-
if (len < 0)
-
printf( "''%s''message Send failure !Error code is %d,Error messages are ''%s''\n", buffer, errno, strerror(errno));
-
-
/* 循环发送文件内容到服务器 */
-
bzero(buffer, MAXBUF + 1);
-
while((size=read(fd,buffer, 1024)))
-
{
-
if(size< 0)
-
{
-
perror( "read:");
-
exit( 1);
-
}
-
else
-
{
-
len = SSL_write(ssl, buffer, size);
-
if (len < 0)
-
printf( "''%s''message Send failure !Error code is %d,Error messages are ''%s''\n", buffer, errno, strerror(errno));
-
}
-
bzero(buffer, MAXBUF + 1);
-
}
-
printf( "Send complete !\n");
-
-
/* 关闭连接 */
-
close(fd);
-
SSL_shutdown(ssl);
-
SSL_free(ssl);
-
close(sockfd);
-
SSL_CTX_free(ctx);
-
return 0;
-
}
-
/*File: server_ssl.c
-
*Auth:sjin
-
*Date:2014-03-11
-
*
-
*/
-
#include <stdio.h>
-
#include <stdlib.h>
-
#include <errno.h>
-
#include <string.h>
-
#include <sys/types.h>
-
#include <netinet/in.h>
-
#include <sys/socket.h>
-
#include <sys/wait.h>
-
#include <unistd.h>
-
#include <arpa/inet.h>
-
#include <sys/types.h>
-
#include <sys/stat.h>
-
#include <fcntl.h>
-
#include <openssl/ssl.h>
-
#include <openssl/err.h>
-
-
#define MAXBUF 1024
-
-
int main(int argc, char **argv)
-
{
-
int sockfd, new_fd, fd;
-
socklen_t len;
-
struct sockaddr_in my_addr, their_addr;
-
unsigned int myport, lisnum;
-
char buf[MAXBUF + 1];
-
char new_fileName[ 50]= "/newfile/";
-
SSL_CTX *ctx;
-
mode_t mode;
-
char pwd[ 100];
-
char* temp;
-
-
/* 在根目录下创建一个 newfile 文件夹 */
-
mkdir( "/newfile",mode);
-
-
if (argv[ 1])
-
myport = atoi(argv[ 1]);
-
else
-
{
-
myport = 7838;
-
argv[ 2]=argv[ 3]= NULL;
-
}
-
-
if (argv[ 2])
-
lisnum = atoi(argv[ 2]);
-
else
-
{
-
lisnum = 2;
-
argv[ 3]= NULL;
-
}
-
-
/* SSL 库初始化 */
-
SSL_library_init();
-
/* 载入所有 SSL 算法 */
-
OpenSSL_add_all_algorithms();
-
/* 载入所有 SSL 错误消息 */
-
SSL_load_error_strings();
-
/* 以 SSL V2 和 V3 标准兼容方式产生一个 SSL_CTX ,即 SSL Content Text */
-
ctx = SSL_CTX_new(SSLv23_server_method());
-
/* 也可以用 SSLv2_server_method () 或 SSLv3_server_method () 单独表示 V2 或 V3 标准 */
-
if (ctx == NULL)
-
{
-
ERR_print_errors_fp( stdout);
-
exit( 1);
-
}
-
/* 载入用户的数字证书, 此证书用来发送给客户端。 证书里包含有公钥 */
-
getcwd(pwd, 100);
-
if( strlen(pwd)== 1)
-
pwd[ 0]= ''\0'';
-
if (SSL_CTX_use_certificate_file(ctx, temp= strcat(pwd, "/cacert.pem"), SSL_FILETYPE_PEM) <= 0)
-
{
-
ERR_print_errors_fp( stdout);
-
exit( 1);
-
}
-
/* 载入用户私钥 */
-
getcwd(pwd, 100);
-
if( strlen(pwd)== 1)
-
pwd[ 0]= ''\0'';
-
if (SSL_CTX_use_PrivateKey_file(ctx, temp= strcat(pwd, "/privkey.pem"), SSL_FILETYPE_PEM) <= 0)
-
{
-
ERR_print_errors_fp( stdout);
-
exit( 1);
-
}
-
/* 检查用户私钥是否正确 */
-
if (!SSL_CTX_check_private_key(ctx))
-
{
-
ERR_print_errors_fp( stdout);
-
exit( 1);
-
}
-
-
/* 开启一个 socket 监听 */
-
if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1)
-
{
-
perror( "socket");
-
exit( 1);
-
}
-
else
-
printf( "socket created\n");
-
-
bzero(&my_addr, sizeof(my_addr));
-
my_addr.sin_family = PF_INET;
-
my_addr.sin_port = htons(myport);
-
if (argv[ 3])
-
my_addr.sin_addr.s_addr = inet_addr(argv[ 3]);
-
else
-
my_addr.sin_addr.s_addr = INADDR_ANY;
-
-
if (bind(sockfd, (struct sockaddr *) &my_addr, sizeof(struct sockaddr)) == -1)
-
{
-
perror( "bind");
-
exit( 1);
-
}
-
else
-
printf( "binded\n");
-
-
if (listen(sockfd, lisnum) == -1)
-
{
-
perror( "listen");
-
exit( 1);
-
}
-
else
-
printf( "begin listen\n");
-
-
while ( 1)
-
{
-
SSL *ssl;
-
len = sizeof(struct sockaddr);
-
/* 等待客户端连上来 */
-
if ((new_fd = accept(sockfd, (struct sockaddr *) &their_addr, &len)) == -1)
-
{
-
perror( "accept");
-
exit(errno);
-
}
-
else
-
printf( "server: got connection from %s, port %d, socket %d\n", inet_ntoa(their_addr.sin_addr), ntohs(their_addr.sin_port), new_fd);
-
-
/* 基于 ctx 产生一个新的 SSL */
-
ssl = SSL_new(ctx);
-
/* 将连接用户的 socket 加入到 SSL */
-
SSL_set_fd(ssl, new_fd);
-
/* 建立 SSL 连接 */
-
if (SSL_accept(ssl) == -1)
-
{
-
perror( "accept");
-
close(new_fd);
-
break;
-
}
-
-
/* 接受客户端所传文件的文件名并在特定目录创建空文件 */
-
bzero(buf, MAXBUF + 1);
-
bzero(new_fileName+ 9, 42);
-
len = SSL_read(ssl, buf, MAXBUF);
-
if(len == 0)
-
printf( "Receive Complete !\n");
-
else if(len < 0)
-
printf( "Failure to receive message ! Error code is %d,Error messages are ''%s''\n", errno, strerror(errno));
-
if((fd = open( strcat(new_fileName,buf),O_CREAT | O_TRUNC | O_RDWR, 0666))< 0)
-
{
-
perror( "open:");
-
exit( 1);
-
}
-
-
/* 接收客户端的数据并写入文件 */
-
while( 1)
-
{
-
bzero(buf, MAXBUF + 1);
-
len = SSL_read(ssl, buf, MAXBUF);
-
if(len == 0)
-
{
-
printf( "Receive Complete !\n");
-
break;
-
}
-
else if(len < 0)
-
{
-
printf( "Failure to receive message ! Error code is %d,Error messages are ''%s''\n", errno, strerror(errno));
-
exit( 1);
-
}
-
if(write(fd,buf,len)< 0)
-
{
-
perror( "write:");
-
exit( 1);
-
}
-
}
-
-
/* 关闭文件 */
-
close(fd);
-
/* 关闭 SSL 连接 */
-
SSL_shutdown(ssl);
-
/* 释放 SSL */
-
SSL_free(ssl);
-
/* 关闭 socket */
-
close(new_fd);
-
}
-
-
/* 关闭监听的 socket */
-
close(sockfd);
-
/* 释放 CTX */
-
SSL_CTX_free(ctx);
-
return 0;
-
}
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 端的设置过程,还是从一下代码来看看如何书写吧。
-
#include <openssl/ssl.h>
-
#include <openssl/crypto.h>
-
#include <openssl/err.h>
-
#include <openssl/bio.h>
-
#include <openssl/pkcs12.h>
-
-
#include <unistd.h>
-
#include <stdio.h>
-
#include <string.h>
-
#include <stdlib.h>
-
#include <errno.h>
-
#include <sys/socket.h>
-
#include <sys/types.h>
-
#include <netinet/in.h>
-
#include <arpa/inet.h>
-
-
#define IP "172.22.14.157"
-
#define PORT 4433
-
#define CERT_PATH "./sslclientcert.pem"
-
#define KEY_PATH "./sslclientkey.pem"
-
#define CAFILE "./demoCA/cacert.pem"
-
static SSL_CTX *g_sslctx = NULL;
-
-
-
int connect_to_server(int fd ,char* ip,int port){
-
struct sockaddr_in svr;
-
memset(&svr,0,sizeof(svr));
-
svr.sin_family = AF_INET;
-
svr.sin_port = htons(port);
-
if(inet_pton(AF_INET,ip,&svr.sin_addr) <= 0){
-
printf("invalid ip address!\n");
-
return -1;
-
}
-
if(connect(fd,(struct sockaddr *)&svr,sizeof(svr))){
-
printf("connect error : %s\n",strerror(errno));
-
return -1;
-
}
-
-
return 0;
-
}
-
-
// 客户端证书内容输出
-
void print_client_cert(char* path)
-
{
-
X509 *cert =NULL;
-
FILE *fp = NULL;
-
fp = fopen(path,"rb");
-
// 从证书文件中读取证书到 x509 结构中,passwd 为 1111, 此为生成证书时设置的
-
cert = PEM_read_X509(fp, NULL, NULL, "1111");
-
X509_NAME *name=NULL;
-
char buf[8192]={0};
-
BIO *bio_cert = NULL;
-
// 证书持有者信息
-
name = X509_get_subject_name(cert);
-
X509_NAME_oneline(name,buf,8191);
-
printf("ClientSubjectName:%s\n",buf);
-
memset(buf,0,sizeof(buf));
-
bio_cert = BIO_new(BIO_s_mem());
-
PEM_write_bio_X509(bio_cert, cert);
-
// 证书内容
-
BIO_read( bio_cert, buf, 8191);
-
printf("CLIENT CERT:\n%s\n",buf);
-
if(bio_cert)BIO_free(bio_cert);
-
fclose(fp);
-
if(cert) X509_free(cert);
-
}
-
// 在 SSL 握手时,验证服务端证书时会被调用,res 返回值为 1 则表示验证成功,否则为失败
-
static int verify_cb(int res, X509_STORE_CTX *xs)
-
{
-
printf("SSL VERIFY RESULT :%d\n",res);
-
switch (xs->error)
-
{
-
case X509_V_ERR_UNABLE_TO_GET_CRL:
-
printf(" NOT GET CRL!\n");
-
return 1;
-
default :
-
break;
-
}
-
return res;
-
}
-
-
int sslctx_init()
-
{
-
#if 0
-
BIO *bio = NULL;
-
X509 *cert = NULL;
-
STACK_OF(X509) *ca = NULL;
-
EVP_PKEY *pkey =NULL;
-
PKCS12* p12 = NULL;
-
X509_STORE *store =NULL;
-
int error_code =0;
-
#endif
-
-
int ret =0;
-
print_client_cert(CERT_PATH);
-
//registers the libssl error strings
-
SSL_load_error_strings();
-
-
//registers the available SSL/TLS ciphers and digests
-
SSL_library_init();
-
-
//creates a new SSL_CTX object as framework to establish TLS/SSL
-
g_sslctx = SSL_CTX_new(SSLv23_client_method());
-
if(g_sslctx == NULL){
-
ret = -1;
-
goto end;
-
}
-
-
//passwd is supplied to protect the private key,when you want to read key
-
SSL_CTX_set_default_passwd_cb_userdata(g_sslctx,"1111");
-
-
//set cipher ,when handshake client will send the cipher list to server
-
SSL_CTX_set_cipher_list(g_sslctx,"HIGH:MEDIA:LOW:!DH");
-
//SSL_CTX_set_cipher_list(g_sslctx,"AES128-SHA");
-
-
//set verify ,when recive the server certificate and verify it
-
//and verify_cb function will deal the result of verification
-
SSL_CTX_set_verify(g_sslctx, SSL_VERIFY_PEER, verify_cb);
-
-
//sets the maximum depth for the certificate chain verification that shall
-
//be allowed for ctx
-
SSL_CTX_set_verify_depth(g_sslctx, 10);
-
-
//load the certificate for verify server certificate, CA file usually load
-
SSL_CTX_load_verify_locations(g_sslctx,CAFILE, NULL);
-
-
//load user certificate,this cert will be send to server for server verify
-
if(SSL_CTX_use_certificate_file(g_sslctx,CERT_PATH,SSL_FILETYPE_PEM) <= 0){
-
printf("certificate file error!\n");
-
ret = -1;
-
goto end;
-
}
-
//load user private key
-
if(SSL_CTX_use_PrivateKey_file(g_sslctx,KEY_PATH,SSL_FILETYPE_PEM) <= 0){
-
printf("privatekey file error!\n");
-
ret = -1;
-
goto end;
-
}
-
if(!SSL_CTX_check_private_key(g_sslctx)){
-
printf("Check private key failed!\n");
-
ret = -1;
-
goto end;
-
}
-
-
end:
-
return ret;
-
}
-
-
void sslctx_release()
-
{
-
EVP_cleanup();
-
if(g_sslctx){
-
SSL_CTX_free(g_sslctx);
-
}
-
g_sslctx= NULL;
-
}
-
// 打印服务端证书相关内容
-
void print_peer_certificate(SSL *ssl)
-
{
-
X509* cert= NULL;
-
X509_NAME *name=NULL;
-
char buf[8192]={0};
-
BIO *bio_cert = NULL;
-
// 获取 server 端证书
-
cert = SSL_get_peer_certificate(ssl);
-
// 获取证书拥有者信息
-
name = X509_get_subject_name(cert);
-
X509_NAME_oneline(name,buf,8191);
-
printf("ServerSubjectName:%s\n",buf);
-
memset(buf,0,sizeof(buf));
-
bio_cert = BIO_new(BIO_s_mem());
-
PEM_write_bio_X509(bio_cert, cert);
-
BIO_read( bio_cert, buf, 8191);
-
//server 证书内容
-
printf("SERVER CERT:\n%s\n",buf);
-
if(bio_cert)BIO_free(bio_cert);
-
if(cert)X509_free(cert);
-
}
-
-
int main(int argc, char** argv){
-
int fd = -1 ,ret = 0;
-
SSL *ssl = NULL;
-
char buf[1024] ={0};
-
// 初始化 SSL
-
if(sslctx_init()){
-
printf("sslctx init failed!\n");
-
goto out;
-
}
-
// 客户端 socket 建立 tcp 连接
-
fd = socket(AF_INET,SOCK_STREAM,0);
-
if(fd < 0){
-
printf("socket error:%s\n",strerror(errno));
-
goto out;
-
}
-
-
if(connect_to_server(fd ,IP,PORT)){
-
printf("can''t connect to server:%s:%d\n",IP,PORT);
-
goto out;
-
}
-
ssl = SSL_new(g_sslctx);
-
if(!ssl){
-
printf("can''t get ssl from ctx!\n");
-
goto out;
-
}
-
SSL_set_fd(ssl,fd);
-
// 建立与服务端 SSL 连接
-
ret = SSL_connect(ssl);
-
if(ret != 1){
-
int err = ERR_get_error();
-
printf("Connect error code: %d ,string: %s\n",err,ERR_error_string(err,NULL));
-
goto out;
-
}
-
// 输入服务端证书内容
-
print_peer_certificate(ssl);
-
-
//SSL_write(ssl,"sslclient test!",strlen("sslclient test!"));
-
//SSL_read(ssl,buf,1024);
-
// 关闭 SSL 连接
-
SSL_shutdown(ssl);
-
-
-
out:
-
if(fd >0)close(fd);
-
if(ssl != NULL){
-
SSL_free(ssl);
-
ssl = NULL;
-
}
-
if(g_sslctx != NULL) sslctx_release();
-
return 0;
-
}
参考资料:
http://www.169it.com/article/3215130236.html
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双向认证的客户端(二)
在上篇文章中写到了如何实现服务端程序,主要是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忽略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】
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代码 收藏代码
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('id' => '2'); $local_cert = "./client-cer.pem"; set_time_limit(0); try{ //ini_set("soap.wsdl_cache_enabled", "0"); // disabling WSDL cache $wsdl='https://192.168.1.146:8443/pro/ws/getInfoService?wsdl'; // echo file_get_contents($wsdl); $soap=new SoapClient($wsdl, array( 'trace'=>true, 'cache_wsdl'=>WSDL_CACHE_NONE, 'soap_version' => SOAP_1_1, 'local_cert' => $local_cert, //client证书信息 'passphrase'=> 'client', //密码 // 'allow_self_signed'=> true ) ); $result=$soap->sayHello($params); $result_json= json_encode($result); $result= json_decode($result_json,true); echo '结果为:' . json_decode($result['return'],true); }catch(Exception $e) { $result['success'] = '0'; $result['msg'] = '请求超时'; echo $e->getMessage(); } echo '>>>>>>>>>>>';
直接运行,也会出现附件中的结果,打完收工,憋了我整整三天时间,终于搞定了。
今天关于SSL 握手通信详解及 linux 下 c/c++ SSL Socket 代码举例 (另附 SSL 双向认证客户端代码)的分享就到这里,希望大家有所收获,若想了解更多关于HttpClient4实现SSL双向认证的客户端(一)、HttpClient4实现SSL双向认证的客户端(二)、IO :: Socket :: SSL似乎忽略了SSL_VERIFY_NONE、java keystore 实现ssl双向认证【客户端为php和java】等相关知识,可以在本站进行查询。
本文标签: