From 31f2e0cba3281660a2a3ffc6f902a7019cb4699b Mon Sep 17 00:00:00 2001 From: Dan McGee Date: Thu, 11 Aug 2011 15:46:18 -0500 Subject: Add ALPM sha256sum routines These mirror ones we already have for md5sums. Signed-off-by: Dan McGee --- lib/libalpm/util.c | 80 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) (limited to 'lib/libalpm/util.c') diff --git a/lib/libalpm/util.c b/lib/libalpm/util.c index adb1d192..d0661289 100644 --- a/lib/libalpm/util.c +++ b/lib/libalpm/util.c @@ -46,8 +46,10 @@ #ifdef HAVE_LIBSSL #include +#include #else #include "md5.h" +#include "sha2.h" #endif /* libalpm */ @@ -747,6 +749,53 @@ static int md5_file(const char *path, unsigned char output[16]) fclose(f); return 0; } + +/* third param is so we match the PolarSSL definition */ +static int sha2_file(const char *path, unsigned char output[32], int is224) +{ + FILE *f; + size_t n; + SHA256_CTX ctx; + unsigned char *buf; + + CALLOC(buf, 8192, sizeof(unsigned char), return 1); + + if((f = fopen(path, "rb")) == NULL) { + free(buf); + return 1; + } + + if(is224) { + SHA224_Init(&ctx); + } else { + SHA256_Init(&ctx); + } + + while((n = fread(buf, 1, sizeof(buf), f)) > 0) { + if(is224) { + SHA224_Update(&ctx, buf, n); + } else { + SHA256_Update(&ctx, buf, n); + } + } + + if(is224) { + SHA224_Final(output, &ctx); + } else { + SHA256_Final(output, &ctx); + } + + memset(&ctx, 0, sizeof(SHA256_CTX)); + free(buf); + + if(ferror(f) != 0) { + fclose(f); + return 2; + } + + fclose(f); + return 0; +} #endif /** Get the md5 sum of file. @@ -799,6 +848,37 @@ int _alpm_test_md5sum(const char *filepath, const char *md5sum) return ret; } +/** Get the sha256 sum of file. + * @param filename name of the file + * @return the checksum on success, NULL on error + * @addtogroup alpm_misc + */ +char SYMEXPORT *alpm_compute_sha256sum(const char *filename) +{ + unsigned char output[32]; + char *sha256sum; + int ret, i; + + ASSERT(filename != NULL, return NULL); + + /* allocate 64 chars plus 1 for null */ + CALLOC(sha256sum, 65, sizeof(char), return NULL); + /* defined above for OpenSSL, otherwise defined in sha2.h */ + ret = sha2_file(filename, output, 0); + + if(ret > 0) { + return NULL; + } + + /* Convert the result to something readable */ + for (i = 0; i < 32; i++) { + /* sprintf is acceptable here because we know our output */ + sprintf(sha256sum +(i * 2), "%02x", output[i]); + } + + return sha256sum; +} + /* Note: does NOT handle sparse files on purpose for speed. */ int _alpm_archive_fgets(struct archive *a, struct archive_read_buffer *b) { -- cgit v1.2.3-24-g4f1b