Home  >  Article  >  Backend Development  >  How to Generate SHA256 Hashes with OpenSSL and C ?

How to Generate SHA256 Hashes with OpenSSL and C ?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-27 01:19:30585browse

How to Generate SHA256 Hashes with OpenSSL and C  ?

Generating SHA256 Hashes with OpenSSL and C

Hashing is a cryptographic technique used to generate a unique fingerprint, or digest, of data. In the case of SHA256 (Secure Hash Algorithm 2, 256-bit), this digest is a 256-bit hexadecimal string. SHA256 is commonly used to check data integrity, verify digital signatures, and store passwords securely.

In this article, we'll walk through how to generate SHA256 hashes using the OpenSSL library and C code.

Include OpenSSL Headers

To get started, ensure that you have the OpenSSL headers available to your C compiler. Typically, you can use the following include statement:

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

Create the SHA256 Context

Next, we need to create a SHA256 context to initialize the hashing process. We can do this with the following code:

<code class="cpp">SHA256_CTX context;
SHA256_Init(&context);</code>

Update the SHA256 Context with Data

To generate a hash, we need to feed the data to be hashed into the SHA256 context. We can do this in chunks using the SHA256_Update() function:

<code class="cpp">SHA256_Update(&context, data, data_length);</code>

Finalize the Hash

Once all the data has been fed to the SHA256 context, we can finalize the hash using the SHA256_Final() function:

<code class="cpp">unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_Final(hash, &context);</code>

The resulting hash is now stored in the hash array.

Convert to a Hexadecimal String

Finally, we need to convert the binary hash to a human-readable hexadecimal string:

<code class="cpp">char hex_hash[65];
for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) {
    sprintf(hex_hash + (i * 2), "%02x", hash[i]);
}
hex_hash[64] = 0;</code>

Example Usage

Now that we have our functions in place, we can use them to generate SHA256 hashes as needed. For example:

<code class="cpp">// Generate a hash for a string
char hash_string[65];
SHA256_string("Hello, world!", hash_string);

// Generate a hash for a file
char hash_file[65];
SHA256_file("path/to/file", hash_file);</code>

This will generate a SHA256 hash for the given string or file and store it in the corresponding buffer.

The above is the detailed content of How to Generate SHA256 Hashes with 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