diff options
Diffstat (limited to 'lib/hmac_sha256.c')
-rw-r--r-- | lib/hmac_sha256.c | 77 |
1 files changed, 77 insertions, 0 deletions
diff --git a/lib/hmac_sha256.c b/lib/hmac_sha256.c new file mode 100644 index 0000000..be7f50a --- /dev/null +++ b/lib/hmac_sha256.c @@ -0,0 +1,77 @@ +/* This file is part of Eclat + Copyright (C) 2012, 2013 Sergey Poznyakoff + + Eclat is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + Eclat is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Eclat. If not, see <http://www.gnu.org/licenses/>. */ + +#include <config.h> +#include "libeclat.h" +#include "sha256.h" +#include <string.h> + +#define IPAD 0x36 +#define OPAD 0x5c + +void +hmac_sha256(const void *text, size_t textlen, + const void *key, size_t keylen, + void *digest) +{ + size_t i; + struct sha256_ctx ctx; + char innerhash[SHA256_DIGEST_SIZE]; + char keybuf[SHA256_DIGEST_SIZE]; + unsigned char ipad[64]; /* inner padding - key ^ ipad[64] */ + unsigned char opad[64]; /* outer padding - key ^ opad[64] */ + unsigned char *kp = (unsigned char *)key; + + /* if key is longer than 64 bytes reset it to key=SHA256(key) */ + if (keylen > 64) { + struct sha256_ctx keyhash; + + sha256_init_ctx(&keyhash); + sha256_process_bytes(key, keylen, &keyhash); + sha256_finish_ctx(&keyhash, keybuf); + key = keybuf; + keylen = sizeof(keybuf); + } + + /* Compute SHA256(K XOR opad, SHA256(K XOR ipad, text)), + where + K is an key, padded to 64 bytes with zeros, + ipad and opad are the respective defines above repeated 64 times + text is the text argument (textlen bytes long) + */ + memset(ipad, IPAD, sizeof(ipad)); + memset(opad, OPAD, sizeof(opad)); + + for (i = 0; i < keylen; i++, kp++) { + ipad[i] ^= *kp; + opad[i] ^= *kp; + } + + /* Compute inner hash */ + sha256_init_ctx(&ctx); + sha256_process_block(ipad, sizeof(ipad), &ctx); + sha256_process_bytes(text, textlen, &ctx); + sha256_finish_ctx(&ctx, innerhash); + + /* Compute outer hash */ + sha256_init_ctx(&ctx); + sha256_process_block(opad, sizeof(opad), &ctx); + sha256_process_bytes(innerhash, sizeof(innerhash), &ctx); + sha256_finish_ctx(&ctx, digest); +} + + + |