Path: blob/master/libs/tomcrypt/src/mac/hmac/hmac_init.c
5972 views
/* LibTomCrypt, modular cryptographic library -- Tom St Denis1*2* LibTomCrypt is a library that provides various cryptographic3* algorithms in a highly modular and flexible manner.4*5* The library is free for all purposes without any express6* guarantee it works.7*/8#include "tomcrypt.h"910/**11@file hmac_init.c12HMAC support, initialize state, Tom St Denis/Dobes Vandermeer13*/1415#ifdef LTC_HMAC1617#define LTC_HMAC_BLOCKSIZE hash_descriptor[hash].blocksize1819/**20Initialize an HMAC context.21@param hmac The HMAC state22@param hash The index of the hash you want to use23@param key The secret key24@param keylen The length of the secret key (octets)25@return CRYPT_OK if successful26*/27int hmac_init(hmac_state *hmac, int hash, const unsigned char *key, unsigned long keylen)28{29unsigned char *buf;30unsigned long hashsize;31unsigned long i, z;32int err;3334LTC_ARGCHK(hmac != NULL);35LTC_ARGCHK(key != NULL);3637/* valid hash? */38if ((err = hash_is_valid(hash)) != CRYPT_OK) {39return err;40}41hmac->hash = hash;42hashsize = hash_descriptor[hash].hashsize;4344/* valid key length? */45if (keylen == 0) {46return CRYPT_INVALID_KEYSIZE;47}4849/* allocate ram for buf */50buf = XMALLOC(LTC_HMAC_BLOCKSIZE);51if (buf == NULL) {52return CRYPT_MEM;53}5455/* allocate memory for key */56hmac->key = XMALLOC(LTC_HMAC_BLOCKSIZE);57if (hmac->key == NULL) {58XFREE(buf);59return CRYPT_MEM;60}6162/* (1) make sure we have a large enough key */63if(keylen > LTC_HMAC_BLOCKSIZE) {64z = LTC_HMAC_BLOCKSIZE;65if ((err = hash_memory(hash, key, keylen, hmac->key, &z)) != CRYPT_OK) {66goto LBL_ERR;67}68keylen = hashsize;69} else {70XMEMCPY(hmac->key, key, (size_t)keylen);71}7273if(keylen < LTC_HMAC_BLOCKSIZE) {74zeromem((hmac->key) + keylen, (size_t)(LTC_HMAC_BLOCKSIZE - keylen));75}7677/* Create the initialization vector for step (3) */78for(i=0; i < LTC_HMAC_BLOCKSIZE; i++) {79buf[i] = hmac->key[i] ^ 0x36;80}8182/* Pre-pend that to the hash data */83if ((err = hash_descriptor[hash].init(&hmac->md)) != CRYPT_OK) {84goto LBL_ERR;85}8687if ((err = hash_descriptor[hash].process(&hmac->md, buf, LTC_HMAC_BLOCKSIZE)) != CRYPT_OK) {88goto LBL_ERR;89}90goto done;91LBL_ERR:92/* free the key since we failed */93XFREE(hmac->key);94done:95#ifdef LTC_CLEAN_STACK96zeromem(buf, LTC_HMAC_BLOCKSIZE);97#endif9899XFREE(buf);100return err;101}102103#endif104105106