openssl 实现https 网页访问

本文提供了一个使用openssl库实现HTTPS网页访问的示例,详细介绍了通信流程,包括初始化、发送HTTP请求、获取状态码和内容,以及资源清理。主要涉及的函数有https_init、https_uninit等。

下面是一个用openssl  实现获取https 网页内容的demo,整个流程比较简单,主要封装的API如下

static int https_init(https_context_t *context,const char* url);
static int https_uninit(https_context_t *context);
static int https_read(https_context_t *context,void* buff,int len);
static int https_write(https_context_t *context,const void* buff,int len);
static int https_get_status_code(https_context_t *context);
static int https_read_content(https_context_t *context,char *resp_contet,int max_len);

通信流程:

1、初始化,解析url资源,创建socket 连接,绑定ssl

2、发送http 请求

3、获取请求返回的状态码

4、获取请求返回的数据

5、销毁动态申请的内存资源

 

为了方便学习,我就把整个代码贴在下面


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <openssl/ssl.h>
#include <openssl/bio.h>

#define HTTP_REQ_LENGTH          512
#define HTTP_RESP_LENGTH         20480

typedef struct
{
    int sock_fd;
    SSL_CTX *ssl_ct;
    SSL *ssl;

    //url 解析出来的信息
    char *host;
    char *path;
    int port;
} https_context_t;

static int https_init(https_context_t *context,const char* url);
static int https_uninit(https_context_t *context);
static int https_read(https_context_t *context,void* buff,int len);
static int https_write(https_context_t *context,const void* buff,int len);
static int https_get_status_code(https_context_t *context);
static int https_read_content(https_context_t *context,char *resp_contet,int max_len);

// http 请求头信息
static char https_header[] =
    "GET %s HTTP/1.1\r\n"
    "Host: %s:%d\r\n"
    "Connection: Close\r\n"
    "Accept: */*\r\n"
    "\r\n";

static char http_req_content[HTTP_REQ_LENGTH] = {0};
static char https_resp_content[HTTP_RESP_LENGTH+1] = {0};

static int create_request_socket(const char* host,const int port)
{
    int sockfd;
    struct hostent *server;
    struct sockaddr_in serv_addr;

    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        printf("[http_demo] create_request_socket create socket fail.\n");
        return -1;
    }

    /* lookup the ip address */
    server = gethostbyname(host);
    if(server == NULL)
    {
        printf("[http_demo] create_request_socket gethostbyname fail.\n");
        close(sockfd);
        return -1;
    }

    memset(&serv_addr,0,sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(port);
    memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);

    if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
    {
        printf("[http_demo] create_request_socket connect fail.\n");
        close(sockfd);
        return -1;
    }
    return sockfd;
}

/**
 * @brief https_parser_url  解析出https 中的域名、端口和路径
 * @param url   需要解析的url
 * @param host  解析出来的域名或者ip
 * @param port  端口,没有时默认返回443
 * @param path  路径,指的是域名后面的位置
 * @return
 */
static int https_parser_url(const char* url,char **host,int *port,char **path)
{
    if(url == NULL || strlen(url) < 9 || host == NULL || path == NULL)
    {
         printf("[https_demo] url or host or path is null.\n");
         return -1;
    }

    //判断是不是 https://
    int i = 0;
    char https_prefix[] = "https://";
    for(i=0;i<8;i++)
    {
        if(url[i] != https_prefix[i])
        {
            printf("[https_demo] illegal url = %s.\n",url);
            return -1;
        }
    }

    const char *temp = url+i;
    while(*temp != '/')  //next /
    {
        if(*temp == '\0')  //
        {
            printf("[https_demo] illegal url = %s.\n",url);
            return -1;
        }
        temp++;
    }

    const char *host_port = url+i;
    while(*host_port != ':' && *host_port != '/')  //找到 :或者 / 结束
    {
        host_port ++;
    }

    int host_len = host_port-url-i;  //减掉https://
    int path_len = strlen(temp);
    char *host_temp = (char *)malloc(host_len + 1);  //多一个字符串结束标识 \0
    if(host_temp == NULL)
    {
        printf("[https_demo] malloc host fail.\n");
        return -1;
    }
    if(*host_port++ == ':')  //url 中有端口
    {
        *port = 0;
        while(*host_port !='/' && *host_port !='\0')  //十进制字符串转成数字
        {
            *port *= 10;
            *port += (*host_port - '0');
            host_port ++;
        }
    }
    else
    {
        *port = 443;
    }

    char *path_temp = (char *)malloc(path_len + 1);  //多一个字符串结束标识 \0
    if(path_temp == NULL)
    {
        printf("[https_demo] malloc path fail.\n");
        free(host_temp);
        return -1;
    }
    memcpy(host_temp,url+i,host_len);
    memcpy(path_temp,temp,path_len);
    host_temp[host_len] = '\0';
    path_temp[path_len] = '\0';
    *host = host_temp;
    *path = path_temp;
    return 0;
}

static int https_init(https_context_t *context,const char* url)
{
    if(context == NULL)
    {
        printf("[https_demo] init https_context_t is null.\n");
        return -1;
    }

    if(https_parser_url(url,&(context->host),&(context->port),&(context->path)))
    {
        printf("[https_demo] https_parser_url fail.\n");
        return -1;
    }

    context->sock_fd = create_request_socket(context->host,context->port);
    if(context->sock_fd < 0)
    {
        printf("[https_demo] create_request_socket fail.\n");
        goto https_init_fail;
    }

    context->ssl_ct = SSL_CTX_new(SSLv23_method());
    if(context->ssl_ct == NULL)
    {
        printf("[https_demo] SSL_CTX_new fail.\n");
        goto https_init_fail;
    }

    context->ssl = SSL_new(context->ssl_ct);
    if(context->ssl == NULL)
    {
        printf("[https_demo] SSL_new fail.\n");
        goto https_init_fail;
    }

    if(SSL_set_fd(context->ssl,context->sock_fd)<0)
    {
        printf("[https_demo] SSL_set_fd fail \n");
    }

    if(SSL_connect(context->ssl) == -1)
    {
        printf("[https_demo] SSL_connect fail.\n");
        goto https_init_fail;
    }
    return 0;
https_init_fail:
    https_uninit(context);
    return -1;
}

static int https_read(https_context_t *context,void* buff,int len)
{
    if(context == NULL || context->ssl == NULL)
    {
        printf("[https_demo] read https_context_t or ssl is null.\n");
        return -1;
    }
    return SSL_read(context->ssl,buff,len);
}

static int https_write(https_context_t *context,const void* buff,int len)
{
    if(context == NULL || context->ssl == NULL)
    {
        printf("[https_demo] write https_context_t or ssl is null.\n");
        return -1;
    }
    return SSL_write(context->ssl,buff,len);
}

static int https_get_status_code(https_context_t *context)
{
    if(context == NULL || context->ssl == NULL)
    {
        printf("[https_demo] get status https_context_t or ssl is null.\n");
        return -1;
    }
    int ret;
    int flag =0;
    int recv_len = 0;
    char res_header[1024] = {0};
    while(recv_len<1023)
    {
        ret = SSL_read(context->ssl, res_header+recv_len, 1);
        if(ret<1)  // recv fail
        {
            break;
        }
        //找到响应头的头部信息, 两个"\r\n"为分割点
        if((res_header[recv_len]=='\r'&&(flag==0||flag==2))||(res_header[recv_len]=='\n'&&(flag==1||flag==3)))
        {
            flag++;
        }
        else
        {
            flag = 0;
        }
        recv_len+=ret;
        if(flag==4)
        {
            break;
        }
    }
    //printf("[http_demo] recv_len=%d res_header = %s.\n",recv_len,res_header);
    /*获取响应头的信息*/
    int status_code = -1;
    char *pos = strstr(res_header, "HTTP/");
    if(pos)
    {
        sscanf(pos, "%*s %d", &status_code);//返回状态码
    }
    return status_code;
}

static int https_read_content(https_context_t *context,char *resp_contet,int max_len)
{
    if(context == NULL || context->ssl == NULL)
    {
        printf("[https_demo] read content https_context_t or ssl is null.\n");
        return -1;
    }
    int ret ;
    int recv_size = 0;
    while(recv_size < max_len)
    {
       ret = SSL_read(context->ssl,resp_contet + recv_size,max_len-recv_size);
       if(ret < 1)
       {
           break;
       }
       recv_size += ret;
    }
    return recv_size;
}

static int https_uninit(https_context_t *context)
{
    if(context == NULL)
    {
        printf("[https_demo] uninit https_context_t is null.\n");
        return -1;
    }

    if(context->host != NULL)
    {
        free(context->host);
        context->host = NULL;
    }
    if(context->path != NULL)
    {
        free(context->path);
        context->path = NULL;
    }

    if(context->ssl != NULL)
    {
        SSL_shutdown(context->ssl);
        //SSl_free(context->ssl);
        context->ssl = NULL;
    }
    if(context->ssl_ct != NULL)
    {
        SSL_CTX_free(context->ssl_ct);
        context->ssl_ct = NULL;
    }
    if(context->sock_fd > 0)
    {
        close(context->sock_fd);
        context->sock_fd = -1;
    }
    return 0;
}

int main()
{
    https_context_t https_ct = {0};
    int ret = SSL_library_init();
    printf("[https_demo] SSL_library_init ret = %d.\n",ret);

    https_init(&https_ct,"https://www.baidu.com/");

    ret = snprintf(http_req_content,HTTP_REQ_LENGTH,https_header,https_ct.path,https_ct.host,https_ct.port);

    ret = https_write(&https_ct,http_req_content,ret);
    printf("[https_demo] https_write ret = %d.\n",ret);

    if(https_get_status_code(&https_ct) == 200)
    {
       ret = https_read_content(&https_ct,https_resp_content,HTTP_RESP_LENGTH);
       if(ret > 0)
       {
           https_resp_content[ret] = '\0';  //字符串结束标识
           printf("[https_demo] https_write https_resp_content = \n %s.\n",https_resp_content);
       }
    }
    https_uninit(&https_ct);
    return 0;
}

 

### 回答1: 要配置Nginx实现HTTPS访问,需要完成以下步骤: 1. 购买SSL证书:首先,你需要购买SSL证书,可以选择自签名证书、免费证书或付费证书,具体选择取决于你的需求和预算。 2. 安装SSL证书:将你获得的证书文件和私钥文件上传到服务器上。 3. 配置Nginx:打开Nginx的配置文件(通常为`/etc/nginx/nginx.conf`)并添加以下代码: ```nginx server { listen 443 ssl; server_name your_domain_name; ssl_certificate /path/to/your_certificate.crt; ssl_certificate_key /path/to/your_private_key.key; location / { # 其它配置项 } } ``` 将`your_domain_name`替换为你的域名,`/path/to/your_certificate.crt`和`/path/to/your_private_key.key`替换为你上传证书的文件路径。 4. 配置SSL协议和密码套件:要增强安全性,可以限制可用的SSL协议和密码套件。在Nginx配置文件中添加以下代码: ```nginx ssl_protocols TLSv1.2 TLSv1.3; ssl_prefer_server_ciphers on; ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256'; ``` 这将只启用TLS 1.2和1.3,并限制密码套件。 5. 重启Nginx:保存Nginx配置文件后,使用`sudo nginx -t`检查配置是否正确,然后使用`sudo service nginx restart`重启Nginx。 现在,你的Nginx服务器就配置好了以实现HTTPS访问。通过在浏览器中输入你的域名,应该能够安全地访问你的网站。 ### 回答2: 要配置Nginx实现HTTPS访问,需要遵循以下步骤: 1. 获取SSL证书:首先,您需要从可信的证书颁发机构(CA)获取SSL证书。这可以是免费的也可以是付费的。证书通常以.pem或.crt文件的形式提供。 2. 配置Nginx:打开Nginx配置文件(通常位于/etc/nginx/nginx.conf)并进行以下更改: - 将服务器块中的监听端口从80改为443,因为HTTPS使用443端口。 - 添加以下SSL相关的配置项: ``` server { listen 443; server_name example.com; ssl on; ssl_certificate /path/to/ssl_certificate.crt; ssl_certificate_key /path/to/private_key.key; # 其他相关配置... } ``` - 将"/path/to/ssl_certificate.crt"替换为SSL证书的路径。 - 将"/path/to/private_key.key"替换为SSL证书的私钥的路径。 3. 重启Nginx:保存并关闭配置文件后,使用以下命令重启Nginx服务使配置生效: ``` sudo systemctl restart nginx ``` 4. 验证配置:使用浏览器访问您站点的HTTPS版本(https://example.com)。如果一切顺利,您应该可以看到锁形图标以及安全的HTTPS连接。 请注意,上述步骤仅适用于简单的HTTPS配置。如果您需要更高级的功能,例如HTTP/2或安全加密套件的配置,您可能需要进行额外的设置。 ### 回答3: 配置Nginx实现HTTPS访问需要以下步骤: 1. 生成SSL证书:首先,我们需要生成一个SSL证书用于加密HTTPS通信。通常可以使用OpenSSL工具来生成自签名证书。运行以下命令来生成私钥和自签名证书:openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /path/to/private.key -out /path/to/certificate.crt 2. 安装Nginx:确保你已经安装了Nginx并正确配置了HTTP访问。 3. 配置SSL参数:在Nginx的配置文件中,找到监听80端口的server块,并在该块下添加以下内容: listen 443 ssl; ssl_certificate /path/to/certificate.crt; ssl_certificate_key /path/to/private.key; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_prefer_server_ciphers on; ssl_session_timeout 10m; ssl_session_cache shared:SSL:10m; 这样配置将会监听443端口,并指定SSL证书和私钥的路径。 4. 重启Nginx服务: sudo service nginx restart 这样Nginx就会重新加载配置文件并生效。 5. 测试HTTPS访问使用浏览器访问你的网站,地址改为https://yourdomain.com,替换yourdomain.com为你的网站域名。如果成功显示了网页内容,就表示HTTPS访问配置成功。 配置Nginx实现HTTPS访问是保护网站安全和数据传输的一种重要措施。使用HTTPS可以加密数据传输,防止信息被窃取或篡改。
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值