]> git.ipfire.org Git - thirdparty/dovecot/core.git/commitdiff
lib: Add hmac helpers
authorAki Tuomi <aki.tuomi@dovecot.fi>
Tue, 29 Nov 2016 21:18:56 +0000 (23:18 +0200)
committerTimo Sirainen <timo.sirainen@dovecot.fi>
Sat, 3 Dec 2016 16:45:02 +0000 (18:45 +0200)
These run hmac for given data with given parameters
and returns stack allocated buffer. They are helpful
when doing lots of HMACs, such as the AWS4 signing
protocol.

src/lib/hmac.c
src/lib/hmac.h

index 52da3b442f8d2b2f95367d7889231bb998495c5a..d3dc09f50190e8f2efd93879e872a9b3dda18663 100644 (file)
@@ -10,6 +10,7 @@
 #include "lib.h"
 #include "hmac.h"
 #include "safe-memset.h"
+#include "buffer.h"
 
 void hmac_init(struct hmac_context *_ctx, const unsigned char *key,
                size_t key_len, const struct hash_method *meth)
@@ -59,3 +60,36 @@ void hmac_final(struct hmac_context *_ctx, unsigned char *digest)
        ctx->hash->loop(ctx->ctxo, digest, ctx->hash->digest_size);
        ctx->hash->result(ctx->ctxo, digest);
 }
+
+buffer_t *t_hmac_data(const struct hash_method *meth,
+                     const unsigned char *key, size_t key_len,
+                     const void *data, size_t data_len)
+{
+       struct hmac_context ctx;
+       i_assert(meth != NULL);
+       i_assert(key != NULL && key_len > 0);
+       i_assert(data != NULL || data_len == 0);
+
+       buffer_t *res = buffer_create_dynamic(pool_datastack_create(), meth->digest_size);
+       hmac_init(&ctx, key, key_len, meth);
+       if (data_len > 0)
+               hmac_update(&ctx, data, data_len);
+       unsigned char *buf = buffer_get_space_unsafe(res, 0, meth->digest_size);
+       hmac_final(&ctx, buf);
+       return res;
+}
+
+buffer_t *t_hmac_buffer(const struct hash_method *meth,
+                       const unsigned char *key, size_t key_len,
+                       const buffer_t *data)
+{
+       return t_hmac_data(meth, key, key_len, data->data, data->used);
+}
+
+buffer_t *t_hmac_str(const struct hash_method *meth,
+                    const unsigned char *key, size_t key_len,
+                    const char *data)
+{
+       return t_hmac_data(meth, key, key_len, data, strlen(data));
+}
+
index 7e68cd0966199b43767816215f334d2665374132..8b0a2806d1577b1f7bb6ee0e36c87242b5530299 100644 (file)
@@ -32,4 +32,14 @@ hmac_update(struct hmac_context *_ctx, const void *data, size_t size)
        ctx->hash->loop(ctx->ctx, data, size);
 }
 
+buffer_t *t_hmac_data(const struct hash_method *meth,
+                     const unsigned char *key, size_t key_len,
+                     const void *data, size_t data_len);
+buffer_t *t_hmac_buffer(const struct hash_method *meth,
+                       const unsigned char *key, size_t key_len,
+                       const buffer_t *data);
+buffer_t *t_hmac_str(const struct hash_method *meth,
+                    const unsigned char *key, size_t key_len,
+                    const char *data);
+
 #endif