1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis
3 * LibTomCrypt is a library that provides various cryptographic
4 * algorithms in a highly modular and flexible manner.
6 * The library is free for all purposes without any express
13 HMAC support, initialize state, Tom St Denis/Dobes Vandermeer
18 #define LTC_HMAC_BLOCKSIZE hash_descriptor[hash].blocksize
21 Initialize an HMAC context.
22 @param hmac The HMAC state
23 @param hash The index of the hash you want to use
24 @param key The secret key
25 @param keylen The length of the secret key (octets)
26 @return CRYPT_OK if successful
28 int hmac_init(hmac_state *hmac, int hash, const unsigned char *key, unsigned long keylen)
31 unsigned long hashsize;
35 LTC_ARGCHK(hmac != NULL);
36 LTC_ARGCHK(key != NULL);
39 if ((err = hash_is_valid(hash)) != CRYPT_OK) {
43 hashsize = hash_descriptor[hash].hashsize;
45 /* valid key length? */
47 return CRYPT_INVALID_KEYSIZE;
50 /* allocate ram for buf */
51 buf = XMALLOC(LTC_HMAC_BLOCKSIZE);
56 /* allocate memory for key */
57 hmac->key = XMALLOC(LTC_HMAC_BLOCKSIZE);
58 if (hmac->key == NULL) {
63 /* (1) make sure we have a large enough key */
64 if(keylen > LTC_HMAC_BLOCKSIZE) {
65 z = LTC_HMAC_BLOCKSIZE;
66 if ((err = hash_memory(hash, key, keylen, hmac->key, &z)) != CRYPT_OK) {
71 XMEMCPY(hmac->key, key, (size_t)keylen);
74 if(keylen < LTC_HMAC_BLOCKSIZE) {
75 zeromem((hmac->key) + keylen, (size_t)(LTC_HMAC_BLOCKSIZE - keylen));
78 /* Create the initialization vector for step (3) */
79 for(i=0; i < LTC_HMAC_BLOCKSIZE; i++) {
80 buf[i] = hmac->key[i] ^ 0x36;
83 /* Pre-pend that to the hash data */
84 if ((err = hash_descriptor[hash].init(&hmac->md)) != CRYPT_OK) {
88 if ((err = hash_descriptor[hash].process(&hmac->md, buf, LTC_HMAC_BLOCKSIZE)) != CRYPT_OK) {
93 /* free the key since we failed */
96 #ifdef LTC_CLEAN_STACK
97 zeromem(buf, LTC_HMAC_BLOCKSIZE);
106 /* ref: $Format:%D$ */
107 /* git commit: $Format:%H$ */
108 /* commit time: $Format:%ai$ */