socket通信安全——openssl
前面学习了https,了解到https用到了tls协议,是介于应用层和传输层之前的一层协议,他主要用来验证身份和安全传输数据。主要的算法都在openssl中,所以我就自己学习了一下openssl,顺便对知识进行巩固。
了解openssl我们需要知道三个概念。
1、对称加密
2、非对称加密
3、单向加密
对称加密
使用AES算法进行加密和解密。双方算法是一样的
但是会存在一个问题,黑客先把你们的解密方式获取到就可以破解你们的信息了。除非你们将加密算法自己协商好。但是这个是不显示的。所以就出现了非对称加密。
非对称加密
非对称加密是使用公钥和私钥的方式,即公钥机密只有私钥才能解开,私钥机密公钥可以解开,公钥在任何人手里都有。
我们可以看,首先我们对服务器身份都没有弄清楚,就直接传输,黑客直接在请求的时侯就伪装成服务器,一直当中间人,发送假消息。所以这样是不安全的,因此我们出现了数字签名(防止数据被修改),但是数字签名也可以被冒充,所以出现了数字证书。这里就不多讲,在我上一篇博客写了数字签名和数字证书的。
单向加密
我们称哈希算法就是单向加密,只能顺着算,不能逆着退。即A通过哈希算法得到B。B用任何方法都不能得到A。当然只是算力不够,也不是说绝对不能反推出来。
例子——对称加密
首先我们用简单的对称机密,对socket传输的数据进行加密,然后再通过对称机密算法解密。
aes.c:AES加密算法文件,有加密和解密
client.c:客户端
server.c:服务器
aes.c
#include <stdio.h>
#include <openssl/aes.h>
#include <stdlib.h>
#include <string.h>
int encrypt(char *input_string, char **encrypt_string)
{
AES_KEY aes;
unsigned char key[AES_BLOCK_SIZE]; // AES_BLOCK_SIZE = 16
unsigned char iv[AES_BLOCK_SIZE]; // init vector
unsigned int len; // encrypt length (in multiple of AES_BLOCK_SIZE)
unsigned int i;
// set the encryption length
len = 0;
if ((strlen(input_string) + 1) % AES_BLOCK_SIZE == 0)
{
len = strlen(input_string) + 1;
}
else
{
len = ((strlen(input_string) + 1) / AES_BLOCK_SIZE + 1) * AES_BLOCK_SIZE;
}
// Generate AES 128-bit key
for (i=0; i<16; ++i) {
key[i] = 32 + i;
}
// Set encryption key
for (i=0; i<AES_BLOCK_SIZE; ++i) {
iv[i] = 0;
}
if (AES_set_encrypt_key(key, 128, &aes) < 0) {
fprintf(stderr,"Unable to set encryption key in AESn");
exit(0);
}
// alloc encrypt_string
*encrypt_string = (unsigned char*)calloc(len, sizeof(unsigned char));
if (*encrypt_string == NULL) {
fprintf(stderr,"Unable to allocate memory for encrypt_stringn");
exit(-1);
}
// encrypt (iv will change)
AES_cbc_encrypt(input_string, *encrypt_string, len, &aes, iv, AES_ENCRYPT);
return len;
}
void decrypt(char *encrypt_string, char **decrypt_string,int len)
{
unsigned char key[AES_BLOCK_SIZE]; // AES_BLOCK_SIZE = 16
unsigned char iv[AES_BLOCK_SIZE]; // init vector
AES_KEY aes;
int i;
// Generate AES 128-bit key
for (i=0; i<16; ++i) {
key[i] = 32 + i;
}
// alloc decrypt_string
*decrypt_string = (unsigned char*)calloc(len, sizeof(unsigned char));
if (*decrypt_string == NULL) {
fprintf(stderr,"Unable to allocate memory for decrypt_stringn");
exit(-1);
}
// Set decryption key
for (i=0; i<AES_BLOCK_SIZE; ++i) {
iv[i] = 0;
}
if (AES_set_decrypt_key(key, 128, &aes) < 0) {
fprintf(stderr,"Unable to set decryption key in AESn");
exit(-1);
}
AES_cbc_encrypt(encrypt_string, *decrypt_string, len, &aes, iv,
AES_DECRYPT);
}
aes.h
#ifndef _ASE_H_
#define _ASE_H_
int encrypt(char *input_string, char **encrypt_string);
void decrypt(char *encrypt_string, char **decrypt_string, int len);
#endif
client.c
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include"aes.h"//add
#include <unistd.h>
int main()
{
int len;
int client_sockfd;
struct sockaddr_in server_addr;
char buffer[BUFSIZ];
char *encrypt_string = NULL;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr("59.110.42.24");
server_addr.sin_port = htons(8899);
if((client_sockfd = socket(PF_INET, SOCK_STREAM, 0)) < 0)
{
perror("socket create failed");
return 1;
}
if(connect(client_sockfd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) < 0)
{
perror("connect failed");
return 1;
}
printf("connect to server \n");
len = read(client_sockfd, buffer, BUFSIZ);
buffer[len] = ' ';
printf("%s\n", buffer);
while(1)
{
printf("enter a data:");
scanf("%s", buffer);
if(!strcmp(buffer,"quit"))
break;
int encrypt_length = encrypt(buffer, &encrypt_string); //add
len = write(client_sockfd, encrypt_string, encrypt_length); //add
len = read(client_sockfd, buffer, sizeof(buffer));
char *decry = NULL;
decrypt(buffer,&decry, sizeof(buffer));
printf("recived:%s\n", decry);
}
close(client_sockfd);
printf("bye");
return 0;
}
server.c
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include"aes.h"//add
#include <unistd.h>
int main()
{
int server_fd;
int client_fd;
int len;
struct sockaddr_in server_addr;
struct sockaddr_in client_addr;
int sin_size;
char buffer[BUFSIZ];
// printf("%d",BUFSIZ);
memset(&server_addr, 0, sizeof(server_addr)); //initialize struct
memset(&server_addr, 0, sizeof(client_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(8899);
if((server_fd = socket(PF_INET, SOCK_STREAM, 0)) < 0) //create server socket
{
perror("socket create failed");
return 1;
}
if(bind(server_fd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) < 0) //bind info on server socket
{
perror("bind failed");
return 1;
}
listen(server_fd, 5); //listen port 9000
sin_size = sizeof(struct sockaddr_in);
if((client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &sin_size)) < 0)
{
perror("accept failed");
return 1;
}
printf("accept client %s\n", inet_ntoa(client_addr.sin_addr));
len = write(client_fd,"Welcome to my servern", 21);
while((len=read(client_fd, buffer, BUFSIZ)) > 0)
{
char *decryto_string = NULL; //add
decrypt(buffer, &decryto_string, sizeof(buffer)); //add
printf("%s\n", decryto_string);
char buf[10];
printf("please input buf:");
scanf("%s",buf);
char *encry = NULL;
int lens = encrypt(buf, &encry);
if(write(client_fd,encry,lens)<0)
{
perror("write");
return 1;
}
}
close(client_fd);
close(server_fd);
return 0;
}
编译
gcc aes.c server.c -o server -lcrypto
gcc aes.c client.c -o client -lcrypto
演示效果
都是经过加密和解密的数据
例子——SSL
SSL这个过程我在上一篇博客写出来了,我们的https通讯就用到SSL,他是位于应用层和传输层之间的一个协议。我们来看看他的服务器和客户端怎么写。
服务器
ssl_server.c
#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 <openssl/ssl.h>
#include <openssl/err.h>
#define MAXBUF 1024
int main(int argc, char **argv)
{
int sockfd, new_fd;
socklen_t len;
struct sockaddr_in my_addr, their_addr;
unsigned int myport, lisnum;
char buf[MAXBUF + 1];
SSL_CTX *ctx;
/* 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);
}
/* 载入用户的数字证书, 此证书用来发送给客户端。 证书里包含有公钥 */
if (SSL_CTX_use_certificate_file(ctx,argv[1], SSL_FILETYPE_PEM) <= 0) {
ERR_print_errors_fp(stdout);
exit(1);
}
/* 载入用户私钥 */
if (SSL_CTX_use_PrivateKey_file(ctx, argv[2], 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));
memset(&my_addr, 0, sizeof(my_addr));
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(8899);
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;
printf("-------------1\n");
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;
}
/* 开始处理每个新连接上的数据收发 */
// strcpy(buf, "hello world!");
/* 接收客户端的消息 */
bzero(buf, MAXBUF + 1);
len = SSL_read(ssl, buf, MAXBUF);
if (len > 0)
printf("memsage '%s' received successful! total %d bytes data received\n",
buf, len);
else
printf
("receive memsage failure!error number %d,error reason:'%s'\n",
errno, strerror(errno));
//发送消息
bzero(buf, MAXBUF + 1);
fgets(buf,MAXBUF+1,stdin);
len = SSL_write(ssl, buf, strlen(buf));
if (len <= 0) {
printf
("memsage'%s'send failure!error number:%d,error reason:'%s'\n",
buf, errno, strerror(errno));
goto finish;
} else
printf("memsage '%s' send successful!total send %d bytes data!\n", buf, len);
/* 处理每个新连接上的数据收发结束 */
finish:
/* 关闭 SSL 连接 */
SSL_shutdown(ssl);
/* 释放 SSL */
SSL_free(ssl);
/* 关闭 socket */
close(new_fd);
}
/* 关闭监听的 socket */
close(sockfd);
/* 释放 CTX */
SSL_CTX_free(ctx);
return 0;
}
}
客户端
ssl_client.c
#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 <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("数字证书信息:\n");
line=X509_NAME_oneline(X509_get_subject_name(cert),0,0);
printf("证书:%s\n",line);
free(line);
line=X509_NAME_oneline(X509_get_issuer_name(cert),0,0);
printf("颁发者:%s\n",line);
free(line);
X509_free(cert);
}else
printf("无证书信息!\n");
}
int main(int argc,char **argv)
{
int sockfd,len;
struct sockaddr_in dest;
char buffer[MAXBUF+1];
SSL_CTX *ctx;//定义两个结构体数据
SSL *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);// 将错误打印到FILE中
exit(1);
}
//创建socket用于tcp通信
if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0){
perror("socket");
exit(errno);
}
if(sockfd < 0){
printf("faild\n");
return -1;
}
printf("socket created\n");
memset(&dest,0,sizeof(dest));
dest.sin_family=AF_INET;
dest.sin_port=htons(8899);//ascii to integer 字符串转化为整形数
//inet_aton 将字符串IP地址转化为32位的网络序列地址
if((inet_aton("127.0.0.1",(struct in_addr *)&dest.sin_addr.s_addr))==0)
{
printf("error ");
exit(errno);
}
//连接服务器
if(connect(sockfd,(struct sockaddr*)&dest,sizeof(dest)) < 0)
{
printf("--------1\n");
perror("Connect ");
exit(errno);
printf("---------2\n");
}
printf("server connected\n");
//基于ctx产生一个新的ssl,建立SSL连接
ssl=SSL_new(ctx);
SSL_set_fd(ssl,sockfd);
if(SSL_connect(ssl)==-1)
ERR_print_errors_fp(stderr);
else{
printf("connect with %s encryption\n",SSL_get_cipher(ssl));
ShowCerts(ssl);
}
bzero(buffer,MAXBUF+1);
fgets(buffer,MAXBUF+1,stdin);
len=SSL_write(ssl,buffer,strlen(buffer));
if(len<0)
printf("memsage send failure");
else
printf("memsage '%s' send success\n",buffer);
memset(buffer,0,MAXBUF+1);
len=SSL_read(ssl,buffer,MAXBUF);
if(len>0)
printf("receive '%s' successful!\n total %d bytes data\n",buffer,len);
else {
printf("receive data failure ,error reason:\n%d :%s ",errno,strerror(errno));
goto finish;
}
finish:
SSL_shutdown(ssl);
SSL_free(ssl);
close(sockfd);
SSL_CTX_free(ctx);
return 0;
}
get_key_csr_gcc.sh
获取私钥和证书、编译
#!/bin/sh
openssl genrsa -out privkey.pem 2048
openssl req -new -x509 -key privkey.pem -out cacert.pem -days 1095
gcc -o client ssl_client.c -lssl -lcrypto -ldl
gcc -o server ssl_server.c -lssl -lcrypto -ldl
运行
server运行我们要传参数的进去,一个是证书一个是私钥
./server cacert.pem privkey.pem
./client
函数讲解
SSL_library_init : 注册了所有在SSL API
OpenSSL_add_all_algorithms : 载加密算法函数和单向散列算法函数
SSL_load_error_strings :该函数为SSL接口和Crypto加密接口加载错误描述字符串