OpenCBDC Transaction Processor
Loading...
Searching...
No Matches
util/common/hash.cpp
Go to the documentation of this file.
1// Copyright (c) 2021 MIT Digital Currency Initiative,
2// Federal Reserve Bank of Boston
3// Distributed under the MIT software license, see the accompanying
4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6#include "hash.hpp"
7
8#include "crypto/sha256.h"
9
10#include <cstring>
11#include <iomanip>
12#include <vector>
13
14namespace cbdc {
15 auto to_string(const hash_t& val) -> std::string {
16 std::stringstream ret;
17 ret << std::hex << std::setfill('0');
18
19 for(const auto& byte : val) {
20 ret << std::setw(2) << static_cast<int>(byte);
21 }
22
23 return ret.str();
24 }
25
26 auto hash_from_hex(const std::string& val) -> hash_t {
27 hash_t ret;
28
29 for(size_t i = 0; i < val.size(); i += 2) {
30 unsigned int v{};
31 std::stringstream s;
32 s << std::hex << val.substr(i, 2);
33 s >> v;
34 ret[i / 2] = static_cast<uint8_t>(v);
35 }
36
37 return ret;
38 }
39
40 auto hash_data(const std::byte* data, size_t len) -> hash_t {
41 hash_t ret;
42 CSHA256 sha;
43
44 auto data_vec = std::vector<unsigned char>(len);
45 std::memcpy(data_vec.data(), data, len);
46 sha.Write(data_vec.data(), len);
47 sha.Finalize(ret.data());
48
49 return ret;
50 }
51}
std::array< unsigned char, cbdc::hash_size > hash_t
SHA256 hash container.
auto hash_data(const std::byte *data, size_t len) -> hash_t
Calculates the SHA256 hash of the specified data.
auto hash_from_hex(const std::string &val) -> hash_t
Parses a hexadecimal representation of a hash.
auto to_string(const hash_t &val) -> std::string
Converts a hash to a hexadecimal string.