Example of https client based on openssl

tags: openssl  access-tok  WeChat public account

Because the WeChat public needs to use https to get access_token, when I started to use http request, I found that it couldn’t work.
I found that it needs to be accessed by https. Because the information in this area feels a little bit less, I will write it again. I also refer to the great god:
I just want one more link to let more people know:

#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>

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

// Simple structure to keep track of the handle, and
// of what needs to be freed later.
typedef struct
{
    int socket;
    SSL *sslHandle;
    SSL_CTX *sslContext;
} connection;

// For this example, we'll be testing on openssl.org
#define SERVER  "183.57.48.62" // api.weixin.qq.com server address
#define PORT 443

// Establish a regular tcp connection
int tcpConnect ()
{
    int error, handle;
    struct hostent *host;
    struct sockaddr_in server;

    host = gethostbyname (SERVER);
    handle = socket (AF_INET, SOCK_STREAM, 0);
    if (handle == -1)
    {
        perror ("Socket");
        handle = 0;
    }
    else
    {
        server.sin_family = AF_INET;
        server.sin_port = htons (PORT);
        server.sin_addr = *((struct in_addr *) host->h_addr);
        bzero (&(server.sin_zero), 8);

        error = connect (handle, (struct sockaddr *) &server,
                         sizeof (struct sockaddr));
        if (error == -1)
        {
            perror ("Connect");
            handle = 0;
        }
    }

    return handle;
}

// Establish a connection using an SSL layer
connection *sslConnect (void)
{
    connection *c;

    c = malloc (sizeof (connection));
    c->sslHandle = NULL;
    c->sslContext = NULL;

    c->socket = tcpConnect ();
    if (c->socket)
    {
        // Register the error strings for libcrypto & libssl
        SSL_load_error_strings ();

        // Register the available ciphers and digests
        SSL_library_init ();
        OpenSSL_add_all_algorithms();

        // New context saying we are a client, and using SSL 2 or 3
        c->sslContext = SSL_CTX_new (SSLv23_client_method ());
        if (c->sslContext == NULL)
            ERR_print_errors_fp (stderr);

        // Create an SSL struct for the connection
        c->sslHandle = SSL_new (c->sslContext);
        if (c->sslHandle == NULL)
            ERR_print_errors_fp (stderr);

        // Connect the SSL struct to our connection
        if (!SSL_set_fd (c->sslHandle, c->socket))
            ERR_print_errors_fp (stderr);

        // Initiate SSL handshake
        if (SSL_connect (c->sslHandle) != 1)
            ERR_print_errors_fp (stderr);
    }
    else
    {
        perror ("Connect failed");
    }

    return c;
}

// Disconnect & free connection struct
void sslDisconnect (connection *c)
{
    if (c->socket)
        close (c->socket);
    if (c->sslHandle)
    {
        SSL_shutdown (c->sslHandle);
        SSL_free (c->sslHandle);
    }
    if (c->sslContext)
        SSL_CTX_free (c->sslContext);

    free (c);
}

// Read all available text from the connection
char *sslRead (connection *c)
{
    const int readSize = 1024;
    char *rc = NULL;
    int received, count = 0;
    char buffer[1024];

    if (c)
    {
        while (1)
        {
            if (!rc)
                rc = malloc (readSize * sizeof (char) + 1);
            else
                rc = realloc (rc, (count + 1) *
                              readSize * sizeof (char) + 1);
            memset(rc,0,readSize + 1);
            received = SSL_read (c->sslHandle, buffer, readSize);
            buffer[received] = '\0';

            if (received > 0)
                strcat (rc, buffer);

            if (received < readSize)
                break;
            count++;
        }
    }

    return rc;
}

// Write text to the connection
void sslWrite (connection *c, char *text)
{
    if (c)
        SSL_write (c->sslHandle, text, strlen (text));
}

// Very basic main: we send GET / and print the response.
int main (int argc, char **argv)
{
    connection *c;
    char *response;

    c = sslConnect ();

    //sslWrite (c, "GET / HTTP/1.1\r\nHost: localhost\r\nconnection: close\r\n\r\n");
    // Remember to write down the appid and secret of your application here.
    sslWrite (c, "GET /cgi-bin/token?grant_type=client_credential&appid=your_appid&"
    "secret=your_secret HTTP/1.1\r\nHost: localhost\r\nconnection: close\r\n\r\n");
    response = sslRead (c);

    printf ("%s\n", response);

    sslDisconnect (c);
    free (response);

    return 0;
}

Reference:
[1] Two examples of https client based on openssl [EB/OL].

Intelligent Recommendation

[CentOS7] Download and install OpenSSL 1.1.1 and simulated client access https

Why download and install openSSL 1.1.1 because it supports TLS1.3 borrowed from the first half of this articlehttps://blog.csdn.net/taobong/article/details/103409250 1. First check the current openssl...

C language Access OpenSSL to implement HTTPS request client

api:https://wenku.baidu.com/view/e8ae8f5f80eb6294dc886c4c.html# gdut17@ubuntu:~/skynet_test/cpp$ gcc https.c -o https -lssl -lcrypto gdut17@ubuntu:~/skynet_test/cpp$ ./https Socket Created Socket Conn...

A complete example of issuing digital certificates based on OpenSSL

There are many online usages of OpenSSL command line. The problem is that most of the articles just use a command line piecemeal, without a complete certificate issuance process. Some are just self-si...

Https configuration practice based on openresty (openssl generates certificate)

The certificate required for HTTPS must be issued by a certification authority. The configuration practice here is also an operation on the technical route. The certificate is generated based on opens...

More Recommendation

Bid-way identity authentication and security communication based on OpenSSL implementation HTTPS

Article catalog I. Overview Two. Code design 2.1 SSL_SERVER.C programming 2.2 SSL_CLIENT.C programming Test I. Overview HTTPS provides secure communication channel based on SSL / TLS, based on certifi...

Use openSSL and open source httplib library to build a local https proxy server and https client

Part I Principles and Environment Construction reference httplib library principle httplib builds a simple server to interact with the browser httplib GitHub 1.0 certmgr certificate management tool Th...

Simple example of Client based on CSOCKET

Step 1: Create a new class, Cclient, whose base class is CSOCKET, and create an object Cclient client1 in the main dialog class Step 2: Create and connect to the server, pay attention to the IP addres...

Based on the OpenSSL tool to complete the self-built CA and a certificate for Server, Client

Article catalog Introduction to a .openssl 1.1 main components 1.2 OpenSSL use 2.RSA key operation 2.1 key generation 2.2 Conversion Command 3. Generate a self-signing certificate 3.1 Generate RSA pri...

Generate CA, server and client certificates based on openssl and Guose algorithm

Reference link Guomi self-signed certificate generation_Sanlei Technology's blog-CSDN blog_Gumimi certificate generation Openssl uses sm2 for self-signing_dong_beijing's blog-CSDN blog_openssl sm Prer...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top