new(utils): add new helper to calculate file sha256sum

Signed-off-by: Melissa Kilby <melissa.kilby.oss@gmail.com>
This commit is contained in:
Melissa Kilby 2024-05-08 12:42:47 +00:00 committed by poiana
parent 44c275dee8
commit 2b80cf85ac
2 changed files with 33 additions and 0 deletions

View File

@ -22,6 +22,7 @@ limitations under the License.
#include <libsinsp/utils.h>
#include <re2/re2.h>
#include <openssl/sha.h>
#include <cstring>
#include <fstream>
@ -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);

View File

@ -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);