From ba706bd508fdbe3e6c971769d0c913b32bf458eb Mon Sep 17 00:00:00 2001 From: Aki Tuomi Date: Mon, 9 Jan 2017 10:43:01 +0200 Subject: [PATCH] lib: Add t_hash helpers for hashing --- src/lib/hash-method.c | 16 ++++++++++++++++ src/lib/hash-method.h | 28 ++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/src/lib/hash-method.c b/src/lib/hash-method.c index 51257ccfed..64d7edb88f 100644 --- a/src/lib/hash-method.c +++ b/src/lib/hash-method.c @@ -48,6 +48,22 @@ static void hash_method_result_size(void *context, unsigned char *result_r) result_r[7] = (*ctx & 0x00000000000000ffULL); } +buffer_t *t_hash_data(const struct hash_method *meth, + const void *data, size_t data_len) +{ + i_assert(meth != NULL); + i_assert(data_len == 0 || data != NULL); + unsigned char ctx[meth->context_size]; + buffer_t *result = buffer_create_dynamic(pool_datastack_create(), + meth->digest_size); + unsigned char *resptr = buffer_append_space_unsafe(result, + meth->digest_size); + meth->init(ctx); + meth->loop(ctx, data == NULL ? "" : data, data_len); + meth->result(ctx, resptr); + return result; +} + static const struct hash_method hash_method_size = { "size", sizeof(uint64_t), diff --git a/src/lib/hash-method.h b/src/lib/hash-method.h index a330e60e52..19c3790394 100644 --- a/src/lib/hash-method.h +++ b/src/lib/hash-method.h @@ -1,6 +1,8 @@ #ifndef HASH_METHOD_H #define HASH_METHOD_H +#include "buffer.h" + struct hash_method { const char *name; /* Number of bytes that must be allocated for context */ @@ -18,4 +20,30 @@ const struct hash_method *hash_method_lookup(const char *name); /* NULL-terminated list of all hash methods */ extern const struct hash_method *hash_methods[]; +/** Simple helpers for digesting (hashing) + + * USAGE: + + buffer_t *result = t_hash_str(hash_method_lookup("sha256"), "hello world"); + const char *hex = binary_to_hex(result->data, result->used); + +*/ + +buffer_t *t_hash_data(const struct hash_method *meth, + const void *data, size_t data_len); + +static inline +buffer_t *t_hash_buffer(const struct hash_method *meth, + const buffer_t *data) +{ + return t_hash_data(meth, data->data, data->used); +} + +static inline +buffer_t *t_hash_str(const struct hash_method *meth, + const char *data) +{ + return t_hash_data(meth, data, strlen(data)); +} + #endif