Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
wine-mirror
GitHub Repository: wine-mirror/wine
Path: blob/master/libs/tomcrypt/src/mac/hmac/hmac_init.c
5972 views
1
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
2
*
3
* LibTomCrypt is a library that provides various cryptographic
4
* algorithms in a highly modular and flexible manner.
5
*
6
* The library is free for all purposes without any express
7
* guarantee it works.
8
*/
9
#include "tomcrypt.h"
10
11
/**
12
@file hmac_init.c
13
HMAC support, initialize state, Tom St Denis/Dobes Vandermeer
14
*/
15
16
#ifdef LTC_HMAC
17
18
#define LTC_HMAC_BLOCKSIZE hash_descriptor[hash].blocksize
19
20
/**
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
27
*/
28
int hmac_init(hmac_state *hmac, int hash, const unsigned char *key, unsigned long keylen)
29
{
30
unsigned char *buf;
31
unsigned long hashsize;
32
unsigned long i, z;
33
int err;
34
35
LTC_ARGCHK(hmac != NULL);
36
LTC_ARGCHK(key != NULL);
37
38
/* valid hash? */
39
if ((err = hash_is_valid(hash)) != CRYPT_OK) {
40
return err;
41
}
42
hmac->hash = hash;
43
hashsize = hash_descriptor[hash].hashsize;
44
45
/* valid key length? */
46
if (keylen == 0) {
47
return CRYPT_INVALID_KEYSIZE;
48
}
49
50
/* allocate ram for buf */
51
buf = XMALLOC(LTC_HMAC_BLOCKSIZE);
52
if (buf == NULL) {
53
return CRYPT_MEM;
54
}
55
56
/* allocate memory for key */
57
hmac->key = XMALLOC(LTC_HMAC_BLOCKSIZE);
58
if (hmac->key == NULL) {
59
XFREE(buf);
60
return CRYPT_MEM;
61
}
62
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) {
67
goto LBL_ERR;
68
}
69
keylen = hashsize;
70
} else {
71
XMEMCPY(hmac->key, key, (size_t)keylen);
72
}
73
74
if(keylen < LTC_HMAC_BLOCKSIZE) {
75
zeromem((hmac->key) + keylen, (size_t)(LTC_HMAC_BLOCKSIZE - keylen));
76
}
77
78
/* Create the initialization vector for step (3) */
79
for(i=0; i < LTC_HMAC_BLOCKSIZE; i++) {
80
buf[i] = hmac->key[i] ^ 0x36;
81
}
82
83
/* Pre-pend that to the hash data */
84
if ((err = hash_descriptor[hash].init(&hmac->md)) != CRYPT_OK) {
85
goto LBL_ERR;
86
}
87
88
if ((err = hash_descriptor[hash].process(&hmac->md, buf, LTC_HMAC_BLOCKSIZE)) != CRYPT_OK) {
89
goto LBL_ERR;
90
}
91
goto done;
92
LBL_ERR:
93
/* free the key since we failed */
94
XFREE(hmac->key);
95
done:
96
#ifdef LTC_CLEAN_STACK
97
zeromem(buf, LTC_HMAC_BLOCKSIZE);
98
#endif
99
100
XFREE(buf);
101
return err;
102
}
103
104
#endif
105
106