From: Florian Zeitz Date: Fri, 16 Sep 2011 00:22:49 +0000 (+0200) Subject: lib: Add hmac-sha1 adapted from hmac-md5 X-Git-Tag: 2.1.rc1~19 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=a3350c34a257a28417c7df10b3fde97af70e4f1f;p=thirdparty%2Fdovecot%2Fcore.git lib: Add hmac-sha1 adapted from hmac-md5 --- diff --git a/src/lib/Makefile.am b/src/lib/Makefile.am index a69ffaec6b..2f06e9357c 100644 --- a/src/lib/Makefile.am +++ b/src/lib/Makefile.am @@ -43,6 +43,7 @@ liblib_la_SOURCES = \ hex-binary.c \ hex-dec.c \ hmac-md5.c \ + hmac-sha1.c \ home-expand.c \ hostpid.c \ imem.c \ diff --git a/src/lib/hmac-sha1.c b/src/lib/hmac-sha1.c new file mode 100644 index 0000000000..fdaa53fc15 --- /dev/null +++ b/src/lib/hmac-sha1.c @@ -0,0 +1,52 @@ +/* + * HMAC-SHA1 (RFC-2104) implementation. + * + * Copyright (c) 2004 Andrey Panin + * Copyright (c) 2011 Florian Zeitz + * + * This software is released under the MIT license. + */ + +#include "lib.h" +#include "hmac-sha1.h" +#include "safe-memset.h" + +void hmac_sha1_init(struct hmac_sha1_context *ctx, + const unsigned char *key, size_t key_len) +{ + int i; + unsigned char sha1key[20]; + unsigned char k_ipad[64]; + unsigned char k_opad[64]; + + if (key_len > 64) { + sha1_get_digest(key, key_len, sha1key); + key = sha1key; + key_len = 20; + } + + memcpy(k_ipad, key, key_len); + memset(k_ipad + key_len, 0, 64 - key_len); + memcpy(k_opad, k_ipad, 64); + + for (i = 0; i < 64; i++) { + k_ipad[i] ^= 0x36; + k_opad[i] ^= 0x5c; + } + + sha1_init(&ctx->ctx); + sha1_loop(&ctx->ctx, k_ipad, 64); + sha1_init(&ctx->ctxo); + sha1_loop(&ctx->ctxo, k_opad, 64); + + safe_memset(k_ipad, 0, 64); + safe_memset(k_opad, 0, 64); +} + +void hmac_sha1_final(struct hmac_sha1_context *ctx, unsigned char *digest) +{ + sha1_result(&ctx->ctx, digest); + + sha1_loop(&ctx->ctxo, digest, 20); + sha1_result(&ctx->ctxo, digest); +} diff --git a/src/lib/hmac-sha1.h b/src/lib/hmac-sha1.h new file mode 100644 index 0000000000..bac429fa00 --- /dev/null +++ b/src/lib/hmac-sha1.h @@ -0,0 +1,22 @@ +#ifndef HMAC_SHA1_H +#define HMAC_SHA1_H + +#include "sha1.h" + +struct hmac_sha1_context { + struct sha1_ctxt ctx, ctxo; +}; + +void hmac_sha1_init(struct hmac_sha1_context *ctx, + const unsigned char *key, size_t key_len); +void hmac_sha1_final(struct hmac_sha1_context *ctx, + unsigned char digest[SHA1_RESULTLEN]); + + +static inline void +hmac_sha1_update(struct hmac_sha1_context *ctx, const void *data, size_t size) +{ + sha1_loop(&ctx->ctx, data, size); +} + +#endif