1
0
Fork 0
mirror of https://git.rwth-aachen.de/acs/public/villas/node/ synced 2025-03-09 00:00:00 +01:00

added sha1sum function to calculate hash of file

This commit is contained in:
Steffen Vogel 2017-03-14 01:46:44 -03:00
parent 607be1dd99
commit edb7059452
4 changed files with 55 additions and 0 deletions

View file

@ -14,6 +14,8 @@
#include <signal.h>
#include <sys/types.h>
#include <openssl/sha.h>
#include "log.h"
#ifdef __GNUC__
@ -229,3 +231,10 @@ void rdtsc_sleep(uint64_t nanosecs, uint64_t start);
/** Register a exit callback for program termination (SIGINT / SIGKILL). */
void signals_init(void (*cb)(int signal, siginfo_t *sinfo, void *ctx));
/** Calculate SHA1 hash of complete file \p f and place it into \p sha1.
*
* @param sha1[out] Must be SHA_DIGEST_LENGTH (20) in size.
* @retval 0 Everything was okay.
*/
int sha1sum(FILE *f, unsigned char *sha1);

View file

@ -18,6 +18,8 @@ LIB_LDLIBS = $(LDLIBS) -ldl -lrt
-include lib/apis/Makefile.inc
-include lib/fpga/Makefile.inc
LIB_PKGS = openssl
######## Node types ########
# Enable Socket node type when libnl3 is available

View file

@ -350,4 +350,25 @@ void signals_init(void (*cb)(int signal, siginfo_t *sinfo, void *ctx))
sigemptyset(&sa_quit.sa_mask);
sigaction(SIGINT, &sa_quit, NULL);
sigaction(SIGTERM, &sa_quit, NULL);
}
int sha1sum(FILE *f, unsigned char *sha1)
{
SHA_CTX c;
char buf[512];
ssize_t bytes;
rewind(f); /* Rewind the file in order to calculate over the whole file. */
SHA1_Init(&c);
bytes = fread(buf, 1, 512, f);
while (bytes > 0) {
SHA1_Update(&c, buf, bytes);
bytes = fread(buf, 1, 512, f);
}
SHA1_Final(sha1, &c);
return 0;
}

View file

@ -59,4 +59,27 @@ Test(utils, version)
cr_assert_eq(version_cmp(&v1, &v1), 0);
cr_assert_gt(version_cmp(&v2, &v1), 0);
cr_assert_lt(version_cmp(&v3, &v4), 0);
}
Test(utils, sha1sum)
{
int ret;
FILE *f = tmpfile();
unsigned char hash[SHA_DIGEST_LENGTH];
unsigned char expected[SHA_DIGEST_LENGTH] = { 0x69, 0xdf, 0x29, 0xdf, 0x1f, 0xf2, 0xd2, 0x5d, 0xb8, 0x68, 0x6c, 0x02, 0x8d, 0xdf, 0x40, 0xaf, 0xb3, 0xc1, 0xc9, 0x4d };
/* Write the first 512 fibonaccia numbers to the file */
for (int i = 0, a = 0, b = 1, c; i < 512; i++, a = b, b = c) {
c = a + b;
fwrite((void *) &c, sizeof(c), 1, f);
}
ret = sha1sum(f, hash);
cr_assert_eq(ret, 0);
cr_assert_arr_eq(hash, expected, SHA_DIGEST_LENGTH);
fclose(f);
}