Skip to content

Commit

Permalink
lib: Add t_hash helpers for hashing
Browse files Browse the repository at this point in the history
  • Loading branch information
cmouse authored and GitLab committed Jan 25, 2017
1 parent bcf421b commit ba706bd
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/lib/hash-method.c
Expand Up @@ -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),
Expand Down
28 changes: 28 additions & 0 deletions 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 */
Expand All @@ -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

0 comments on commit ba706bd

Please sign in to comment.