util: add a SHA256 function

This commit is contained in:
moneromooo-monero 2017-02-20 20:46:50 +00:00
parent 4bf7849297
commit 216f062eb8
No known key found for this signature in database
GPG key ID: 686F07454D6CEFC3
3 changed files with 37 additions and 1 deletions

View file

@ -76,6 +76,7 @@ target_link_libraries(common
PUBLIC
epee
crypto
-lcrypto
${UNBOUND_LIBRARY}
${LIBUNWIND_LIBRARIES}
${Boost_DATE_TIME_LIBRARY}

View file

@ -31,6 +31,7 @@
#include <cstdio>
#include "include_base_utils.h"
#include "file_io_utils.h"
using namespace epee;
#include "util.h"
@ -46,7 +47,7 @@ using namespace epee;
#endif
#include <boost/filesystem.hpp>
#include <boost/asio.hpp>
#include <openssl/sha.h>
namespace tools
{
@ -585,4 +586,36 @@ std::string get_nix_version_display_string()
}
return 0;
}
bool sha256sum(const std::string &filename, crypto::hash &hash)
{
if (!epee::file_io_utils::is_file_exist(filename))
return false;
std::ifstream f;
f.exceptions(std::ifstream::failbit | std::ifstream::badbit);
f.open(filename, std::ios_base::binary | std::ios_base::in | std::ios::ate);
if (!f)
return false;
std::ifstream::pos_type file_size = f.tellg();
SHA256_CTX ctx;
if (!SHA256_Init(&ctx))
return false;
size_t size_left = file_size;
f.seekg(0, std::ios::beg);
while (size_left)
{
char buf[4096];
std::ifstream::pos_type read_size = size_left > sizeof(buf) ? sizeof(buf) : size_left;
f.read(buf, read_size);
if (!f || !f.good())
return false;
if (!SHA256_Update(&ctx, buf, read_size))
return false;
size_left -= read_size;
}
f.close();
if (!SHA256_Final((unsigned char*)hash.data, &ctx))
return false;
return true;
}
}

View file

@ -184,4 +184,6 @@ namespace tools
bool is_local_address(const std::string &address);
int vercmp(const char *v0, const char *v1); // returns < 0, 0, > 0, similar to strcmp, but more human friendly than lexical - does not attempt to validate
bool sha256sum(const std::string &filename, crypto::hash &hash);
}