Skip to content

Commit

Permalink
Update SHA256 function for OpenSSL 3.0
Browse files Browse the repository at this point in the history
  • Loading branch information
who-biz committed Sep 8, 2023
1 parent b122b21 commit febd0b1
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/common/util.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,10 @@ using namespace epee;
#include <openssl/ssl.h>
#include <openssl/opensslv.h>

#if OPENSSL_VERSION_NUMBER >= 0x030000000 // 3.0.0
#include <openssl/evp.h>
#endif

namespace tools
{
std::function<void(int)> signal_handler::m_handler;
Expand Down Expand Up @@ -716,6 +720,9 @@ std::string get_nix_version_display_string()

bool sha256sum(const uint8_t *data, size_t len, crypto::hash &hash)
{
#if OPENSSL_VERSION_NUMBER >= 0x030000000 // 3.0.0
return EVP_Digest(data, len, (unsigned char*)hash.data, NULL, EVP_sha256(), NULL);
#else
SHA256_CTX ctx;
if (!SHA256_Init(&ctx))
return false;
Expand All @@ -724,6 +731,7 @@ std::string get_nix_version_display_string()
if (!SHA256_Final((unsigned char*)hash.data, &ctx))
return false;
return true;
#endif
}

bool sha256sum(const std::string &filename, crypto::hash &hash)
Expand All @@ -736,9 +744,17 @@ std::string get_nix_version_display_string()
if (!f)
return false;
std::ifstream::pos_type file_size = f.tellg();


#if OPENSSL_VERSION_NUMBER < 0x030000000 // 3.0.0
SHA256_CTX ctx;
if (!SHA256_Init(&ctx))
return false;
#else
std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)> ctx(EVP_MD_CTX_new(), &EVP_MD_CTX_free);
if (!EVP_DigestInit_ex(ctx.get(), EVP_sha256(), nullptr))
return false;
#endif
size_t size_left = file_size;
f.seekg(0, std::ios::beg);
while (size_left)
Expand All @@ -748,13 +764,23 @@ std::string get_nix_version_display_string()
f.read(buf, read_size);
if (!f || !f.good())
return false;
#if OPENSSL_VERSION_NUMBER < 0x030000000 // 3.0.0
if (!SHA256_Update(&ctx, buf, read_size))
return false;
#else
if (!EVP_DigestUpdate(ctx.get(), buf, read_size))
return false;
#endif
size_left -= read_size;
}
f.close();
#if OPENSSL_VERSION_NUMBER < 0x030000000 // 3.0.0
if (!SHA256_Final((unsigned char*)hash.data, &ctx))
return false;
#else
if (!EVP_DigestFinal_ex(ctx.get(), (unsigned char*)hash.data, nullptr))
return false;
#endif
return true;
}

Expand Down

0 comments on commit febd0b1

Please sign in to comment.