Skip to content

Commit

Permalink
new(utils): add new helper to calculate file sha256sum
Browse files Browse the repository at this point in the history
Signed-off-by: Melissa Kilby <[email protected]>
  • Loading branch information
incertum committed May 8, 2024
1 parent 62d1c4f commit b9b1ee9
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
31 changes: 31 additions & 0 deletions userspace/engine/falco_utils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ limitations under the License.
#include <libsinsp/utils.h>

#include <re2/re2.h>
#include <openssl/sha.h>

#include <cstring>
#include <fstream>
Expand Down Expand Up @@ -117,6 +118,36 @@ uint64_t parse_prometheus_interval(std::string interval_str)
return interval;
}

std::string calculate_file_sha256sum(const std::string& filename)
{
std::ifstream file(filename, std::ios::binary);
if (!file.is_open())
{
return "";
}

SHA256_CTX sha256_context;
SHA256_Init(&sha256_context);

constexpr size_t buffer_size = 4096;
char buffer[buffer_size];
while (file.read(buffer, buffer_size))
{
SHA256_Update(&sha256_context, buffer, buffer_size);
}
SHA256_Update(&sha256_context, buffer, file.gcount());

unsigned char digest[SHA256_DIGEST_LENGTH];
SHA256_Final(digest, &sha256_context);

std::stringstream ss;
for (int i = 0; i < SHA256_DIGEST_LENGTH; ++i)
{
ss << std::hex << std::setw(2) << std::setfill('0') << static_cast<unsigned>(digest[i]);
}
return ss.str();
}

std::string wrap_text(const std::string& in, uint32_t indent, uint32_t line_len)
{
std::istringstream is(in);
Expand Down
2 changes: 2 additions & 0 deletions userspace/engine/falco_utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ namespace falco::utils
{
uint64_t parse_prometheus_interval(std::string interval_str);

std::string calculate_file_sha256sum(const std::string& filename);

std::string wrap_text(const std::string& in, uint32_t indent, uint32_t linelen);

void readfile(const std::string& filename, std::string& data);
Expand Down

0 comments on commit b9b1ee9

Please sign in to comment.