Home > Backend Development > C++ > body text

How to Generate SHA256 Hashes with OpenSSL and C : A Solution for Missing Functions?

Susan Sarandon
Release: 2024-10-26 18:39:30
Original
366 people have browsed it

How to Generate SHA256 Hashes with OpenSSL and C  :  A Solution for Missing Functions?

Generating SHA256 Hashes with OpenSSL and C

When tasked with creating a hash using SHA256 with OpenSSL and C , understanding the library's capabilities becomes crucial. One such instance encountered an issue with missing OpenSSL functions despite including the necessary header files and build paths. The following code snippet illustrates the solution:

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

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;
}

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>
Copy after login

To utilize this code, follow these steps:

<code class="cpp">static unsigned char buffer[65];
sha256("string", buffer);
printf("%s\n", buffer);</code>
Copy after login

This approach effectively generates SHA256 hashes using OpenSSL and C , resolving the include path issue encountered earlier.

The above is the detailed content of How to Generate SHA256 Hashes with OpenSSL and C : A Solution for Missing Functions?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!