]> git.ipfire.org Git - thirdparty/dovecot/core.git/commitdiff
lib: Add t_hash helpers for hashing
authorAki Tuomi <aki.tuomi@dovecot.fi>
Mon, 9 Jan 2017 08:43:01 +0000 (10:43 +0200)
committerGitLab <gitlab@git.dovecot.net>
Wed, 25 Jan 2017 11:19:27 +0000 (13:19 +0200)
src/lib/hash-method.c
src/lib/hash-method.h

index 51257ccfed154a179d51ef7f258a590ef72f1904..64d7edb88fc2a08bdf813a16a578774288012fa1 100644 (file)
@@ -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),
index a330e60e52fa585c124c8b5c5e7602f33e374535..19c3790394f00dca8d6305543071219049e38a9a 100644 (file)
@@ -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