Austin Schuh | b0e439d | 2023-05-15 10:55:40 -0700 | [diff] [blame] | 1 | #include "aos/sha256.h" |
| 2 | |
| 3 | #include <iomanip> |
| 4 | #include <sstream> |
| 5 | #include <string> |
| 6 | |
| 7 | #include "absl/types/span.h" |
| 8 | #include "openssl/sha.h" |
| 9 | |
James Kuszmaul | 56802ab | 2023-08-23 15:18:34 -0700 | [diff] [blame^] | 10 | #include "aos/util/file.h" |
| 11 | |
Austin Schuh | b0e439d | 2023-05-15 10:55:40 -0700 | [diff] [blame] | 12 | namespace aos { |
| 13 | |
| 14 | std::string Sha256(const absl::Span<const uint8_t> str) { |
| 15 | unsigned char hash[SHA256_DIGEST_LENGTH]; |
| 16 | SHA256_CTX sha256; |
| 17 | SHA256_Init(&sha256); |
| 18 | SHA256_Update(&sha256, str.data(), str.size()); |
| 19 | SHA256_Final(hash, &sha256); |
| 20 | std::stringstream ss; |
| 21 | for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) { |
| 22 | ss << std::hex << std::setw(2) << std::setfill('0') |
| 23 | << static_cast<int>(hash[i]); |
| 24 | } |
| 25 | return ss.str(); |
| 26 | } |
| 27 | |
James Kuszmaul | 56802ab | 2023-08-23 15:18:34 -0700 | [diff] [blame^] | 28 | std::string Sha256(std::string_view str) { |
| 29 | return Sha256({reinterpret_cast<const uint8_t *>(str.data()), str.size()}); |
| 30 | } |
| 31 | |
| 32 | std::string Sha256OfFile(std::filesystem::path file) { |
| 33 | const std::string contents = aos::util::ReadFileToStringOrDie(file.string()); |
| 34 | return Sha256(contents); |
| 35 | } |
| 36 | |
Austin Schuh | b0e439d | 2023-05-15 10:55:40 -0700 | [diff] [blame] | 37 | } // namespace aos |