blob: cfeccde6951d9e26524a310d5555ad324c837b36 [file] [log] [blame]
Austin Schuhb0e439d2023-05-15 10:55:40 -07001#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 Kuszmaul56802ab2023-08-23 15:18:34 -070010#include "aos/util/file.h"
11
Austin Schuhb0e439d2023-05-15 10:55:40 -070012namespace aos {
13
14std::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 Kuszmaul56802ab2023-08-23 15:18:34 -070028std::string Sha256(std::string_view str) {
29 return Sha256({reinterpret_cast<const uint8_t *>(str.data()), str.size()});
30}
31
32std::string Sha256OfFile(std::filesystem::path file) {
33 const std::string contents = aos::util::ReadFileToStringOrDie(file.string());
34 return Sha256(contents);
35}
36
Austin Schuhb0e439d2023-05-15 10:55:40 -070037} // namespace aos