diff options
author | moneromooo-monero <moneromooo-monero@users.noreply.github.com> | 2017-02-20 20:46:50 +0000 |
---|---|---|
committer | moneromooo-monero <moneromooo-monero@users.noreply.github.com> | 2017-02-20 22:58:33 +0000 |
commit | 216f062eb875eb0769d63c65ed0f5c8de51a9590 (patch) | |
tree | 514e2bae17a6f8ad056914f26e950fb0df9e662c /src/common/util.cpp | |
parent | mlog: only silence errors for net by default, not net.* (diff) | |
download | monero-216f062eb875eb0769d63c65ed0f5c8de51a9590.tar.xz |
util: add a SHA256 function
Diffstat (limited to 'src/common/util.cpp')
-rw-r--r-- | src/common/util.cpp | 35 |
1 files changed, 34 insertions, 1 deletions
diff --git a/src/common/util.cpp b/src/common/util.cpp index 2741497d6..90748ddb1 100644 --- a/src/common/util.cpp +++ b/src/common/util.cpp @@ -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; + } } |