国密SSL协议之C语言编程

背景

    OpenSSL支持标准的SSL协议,但并不支持国密SSL协议。本文描述了C语言使用国密版OpenSSL开发一个简单的客户端程序,连接国密Web网站,发送HTTP请求,并接收HTTP应答。

环境

Centos7 X64。
国密OpenSSL。下载参https://www.gmssl.cn/gmssl/index.jsp?go=gmsdk
将国密OpenSSL 展开为/usr/local/gmssl_10

源码

#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>

#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/gm.h>

#define MAXBUF 4096

int main(int argc, char *argv[])
{
    struct sockaddr_in serveraddr;
    struct hostent *host;
    int sockfd, len;
    SSL *ssl = NULL;
    int bi = 0;

    if (argc < 4) {
        printf("./%s addr port uri sig.pem sig.key enc.pem enc.key\n", argv[0]);
        printf("optional: sig.pem sig.key enc.pem enc.key\n");
        exit(1);
    }

    if (argc == 8)
    {
        bi = 1;
    }

    char *addr = argv[1];
    int port = atoi(argv[2]);
    char *uri = argv[3];
    char *sigCrt = argv[4];
    char *sigKey = argv[5];
    char *encCrt = argv[6];
    char *encKey = argv[7];

    // 国密SSL初始化
    GM_load_library();

    // 国密SSL生成SSL_CTX
    const SSL_METHOD *method = GMv1_1_client_method();
    SSL_CTX *ctx = SSL_CTX_new(method);
    if (!ctx)
    {
        printf("create ctx is failed.\n");
        exit(1);
    }
    // load gm sign keypair
    if(bi)
    {
            if (SSL_CTX_use_certificate_chain_file(ctx, sigCrt) <= 0)
            {
                printf("unable to get certificate from '%s'\n",sigCrt);
                //ERR_print_errors(bio_err);
                exit(1);
            }
            if (SSL_CTX_use_PrivateKey_file(ctx, sigKey, SSL_FILETYPE_PEM) <= 0)
            {
                printf("unable to get private key from '%s'\n",sigKey);
                //ERR_print_errors(bio_err);
                exit(1);
            }
    }
    // load gm enc keypair
    if(bi)
    {
            if (SSL_CTX_use_encrypt_cert_file(ctx, encCrt) <= 0)
            {
                printf("unable to get certificate(enc) from '%s'\n",encCrt);
                //ERR_print_errors(bio_err);
                exit(1);
            }
            if (SSL_CTX_use_encrypt_PrivateKey_file(ctx, encKey, SSL_FILETYPE_PEM) <= 0)
            {
                printf("unable to get private key(enc) from '%s'\n",encKey);
                //ERR_print_errors(bio_err);
                exit(1);
            }
    }

    if((host = gethostbyname(addr))==0)
    {
        printf("Error resolving host %s\n", addr);
        exit(1);
    }

    char *ip = inet_ntoa(*(struct in_addr*)host->h_addr_list[0]);
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    bzero(&serveraddr, sizeof(serveraddr));
    serveraddr.sin_family = AF_INET;
    inet_pton(AF_INET, ip, &serveraddr.sin_addr.s_addr);
    serveraddr.sin_port  = htons(port);
    int ok = connect(sockfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr));
    if(ok != 0)
    {
        printf("connnect failed\n");
        exit(0);
    }

    ssl = SSL_new(ctx);
    if (ssl == NULL) {
        printf("SSL_new error.\n");
        exit(0);
    }
    SSL_set_fd(ssl, sockfd);
    if (SSL_connect(ssl) == -1) {
        printf("SSL_connect fail.\n");
        ERR_print_errors_fp(stderr);
        exit(1);
    }
    else 
    {
        printf("Connected with %s encryption\n", SSL_get_cipher(ssl));
    }

    // send http request
    {
        char request[1024] = { 0 };
        sprintf(request, "GET %s HTTP/1.1\r\nAccept: */*\r\nUser-Agent: Mozilla/5.0\r\nHost: %s:%s\r\nConnection: close\r\n\r\n", argv[3], argv[1], argv[2]);
        len = SSL_write(ssl, request, strlen(request));
        if (len < 0)
        {
            printf("send failed\n");
        }
        else
        {
            printf("send OK, %d bytes:\n%s\n", strlen(request), request);
        }
    }

    // read http response
    {
        char buffer[MAXBUF + 1];
        memset(buffer, 0, MAXBUF + 1);
        len = SSL_read(ssl, buffer, MAXBUF);
        if (len > 0) {
            printf("read OK, %d bytes: \n%s\n", len, buffer);
        }
        else
        {
            printf("recv failed\n");
            goto finish;
        }
    }

finish:
    SSL_shutdown(ssl);
    SSL_free(ssl);
    close(sockfd);
    SSL_CTX_free(ctx);

    return 0;
}

测试运行

编译
gcc -o test -ldl -lm test.c /usr/local/gmssl_10/lib/libssl.a /usr/local/gmssl_10/lib/libcrypto.a -I/usr/local/gmssl_10/include
运行
单向国密SSL网站
./test demo.gmssl.cn 443 /
双向国密SSL网站
./test demo.gmssl.cn 444 /cert.jsp sig.crt sig.key enc.crt enc.key

备注

1)搭建单向/双向国密web服务器,可以参见https://www.gmssl.cn,提供nginx/apache/tomcat支持。
2)申请国密双证书,参见https://www.gmssl.cn/gmssl/index.jsp?go=ca
3)https://demo.gmssl.cn是一个单向国密Web网站
4)https://demo.gmssl.cn:444是一个双向国密Web网站

小结

  通过使用国密OpenSSL,C语言很容易编程来使用国密SSL连接国密Web网站。www.gmssl.cn提供了全部免费的测试组件,并且支持双向国密SSL,可供学习和测试。

上一篇:增加VMware虚拟机的磁盘空间


下一篇:从时间和空间角度浅谈VMware虚拟机启动全过程