From 427d06c98744dad1945430e45c5eea165c90b373 Mon Sep 17 00:00:00 2001 From: Benjamin Valentin Date: Sat, 30 Apr 2022 18:14:20 +0200 Subject: [PATCH] sys/vfs_util: add vfs_file_sha256() --- sys/include/vfs_util.h | 16 ++++++++++++++++ sys/vfs_util/vfs_util.c | 24 ++++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/sys/include/vfs_util.h b/sys/include/vfs_util.h index 594070e89b..a6ae1ec911 100644 --- a/sys/include/vfs_util.h +++ b/sys/include/vfs_util.h @@ -83,6 +83,22 @@ int vfs_file_md5(const char* file, void *digest, */ int vfs_file_sha1(const char* file, void *digest, void *work_buf, size_t work_buf_len); + +/** + * @brief Compute the SHA256 message digest of a file + * + * Requires the `hashes` module. + * + * @param[in] file Source file path + * @param[out] digest Destination buffer, must fit @ref SHA256_DIGEST_LENGTH bytes + * @param[out] work_buf Work buffer + * @param[in] work_buf_len Size of the work buffer + * + * @return 0 on success + * @return negative error + */ +int vfs_file_sha256(const char* file, void *digest, + void *work_buf, size_t work_buf_len); #endif #ifdef __cplusplus diff --git a/sys/vfs_util/vfs_util.c b/sys/vfs_util/vfs_util.c index a8f3585a95..adf7e7f13f 100644 --- a/sys/vfs_util/vfs_util.c +++ b/sys/vfs_util/vfs_util.c @@ -83,6 +83,7 @@ int vfs_file_to_buffer(const char* file, void* buf, size_t len) #if MODULE_HASHES #include "hashes/md5.h" #include "hashes/sha1.h" +#include "hashes/sha256.h" int vfs_file_md5(const char* file, void *digest, void *work_buf, size_t work_buf_len) @@ -128,5 +129,28 @@ int vfs_file_sha1(const char* file, void *digest, return res > 0 ? 0 : res; +} + +int vfs_file_sha256(const char* file, void *digest, + void *work_buf, size_t work_buf_len) +{ + sha256_context_t ctx; + int res, fd = vfs_open(file, O_RDONLY, 0); + + if (fd < 0) { + DEBUG("can't open %s for reading\n", file); + return fd; + } + + sha256_init(&ctx); + while ((res = vfs_read(fd, work_buf, work_buf_len)) > 0) { + sha256_update(&ctx, work_buf, res); + } + sha256_final(&ctx, digest); + + vfs_close(fd); + + return res > 0 ? 0 : res; + } #endif /* MODULE_HASHES */