Write a C language program to call the dynamic link library compiled by openssl

1. Compile and generate link library

The process of downloading, installing openssl and compiling and generating link libraries has been explained in detail in another article of mine: Installing OpenSSL in Ubuntu

In addition, we also need to know some knowledge about dynamic link libraries in advance. The specific content can be viewed in my article: A simple dynamic link library example

2. Example 1: Calling the RAND_bytes function

To call functions in the OpenSSL library, you need to include the corresponding header file in the corresponding C source file and link the library file into the program.

Below is a simple example that demonstrates how to use functions from the OpenSSL library in a file called main.c.

#include <stdio.h>  
#include <openssl/rand.h>  
  
int main() {
    
      
    // 生成一个随机的字节序列  
    unsigned char randomBytes[16];  
    RAND_bytes(randomBytes, sizeof(randomBytes));  
  
    // 打印生成的随机字节序列  
    printf("随机字节序列: ");  
    for (int i = 0; i < sizeof(randomBytes); i++) {
    
      
        printf("%02x", randomBytes[i]);  
    }  
    printf("\n");  
  
    return 0;  
}

In this example, the openssl/rand.h header file is introduced, which contains the declaration of the RAND_bytes function. Then, in the main function, the RAND_bytes function is called to generate a random byte sequence and print it out.

To compile and link this program, the OpenSSL library files need to be linked to the program. You can use the following command to compile and execute

gcc -o main main.c -lssl -lcrypto
./main

The corresponding output results can be obtained

Insert image description here

3. Example 2: Calling SHA256

First create a new main1.c file and write the following code

#include <stdio.h>  
#include <openssl/sha.h>  
  
int main() {
    
      
    unsigned char data[] = "Hello, World!";  
    unsigned char sha256_result[SHA256_DIGEST_LENGTH];  
    SHA256(data, strlen((char*)data), sha256_result);  
    printf("SHA256 Result: ");  
    for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) {
    
      
        printf("%02x", sha256_result[i]);  
    }  
    printf("\n");  
    return 0;  
}

After compiling and executing, you can get the corresponding results.

gcc -o main1 main1.c -lssl -lcrypto
./main1

Guess you like

Origin blog.csdn.net/weixin_46841376/article/details/132498585