Home  >  Article  >  Backend Development  >  How can you generate SHA256 hashes using OpenSSL and C ?

How can you generate SHA256 hashes using OpenSSL and C ?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-30 00:58:02762browse

How can you generate SHA256 hashes using OpenSSL and C  ?

Generate SHA256 with OpenSSL and C

In this article, we will explore how to generate SHA256 hashes using the OpenSSL library and C . SHA256 is a widely used cryptographic hash function that produces a unique 256-bit digest of arbitrary data.

Implementation

To begin, we need to ensure that the OpenSSL development libraries and headers are available on our system. After including the necessary headers, we can proceed with the implementation:

<code class="cpp">#include <openssl/sha.h>

// Function to generate SHA256 hash of a string
void sha256_string(char *string, char outputBuffer[65]) {
    unsigned char hash[SHA256_DIGEST_LENGTH];
    SHA256_CTX sha256;
    SHA256_Init(&sha256);
    SHA256_Update(&sha256, string, strlen(string));
    SHA256_Final(hash, &sha256);
    int i = 0;
    for (i = 0; i < SHA256_DIGEST_LENGTH; i++) {
        sprintf(outputBuffer + (i * 2), "%02x", hash[i]);
    }
    outputBuffer[64] = 0;
}</code>

To generate a SHA256 hash from a file, we use the following function:

<code class="cpp">int sha256_file(char *path, char outputBuffer[65]) {
    FILE *file = fopen(path, "rb");
    if (!file) return -534;

    unsigned char hash[SHA256_DIGEST_LENGTH];
    SHA256_CTX sha256;
    SHA256_Init(&sha256);
    const int bufSize = 32768;
    unsigned char *buffer = malloc(bufSize);
    int bytesRead = 0;
    if (!buffer) return ENOMEM;
    while ((bytesRead = fread(buffer, 1, bufSize, file))) {
        SHA256_Update(&sha256, buffer, bytesRead);
    }
    SHA256_Final(hash, &sha256);

    sha256_hash_string(hash, outputBuffer);
    fclose(file);
    free(buffer);
    return 0;
}</code>

To use these functions, simply pass the input string or file path as an argument. The generated SHA256 hash will be returned in the provided output buffer.

The above is the detailed content of How can you generate SHA256 hashes using OpenSSL and C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn