]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - hmac.c
host: Check !host.restless instead of !cls.demoplayback for rand() call
[xonotic/darkplaces.git] / hmac.c
1 #include "quakedef.h"
2 #include "hmac.h"
3
4 qboolean hmac(
5         hashfunc_t hfunc, int hlen, int hblock,
6         unsigned char *out,
7         const unsigned char *in, int n,
8         const unsigned char *key, int k
9 )
10 {
11         unsigned char hashbuf[32];
12         unsigned char k_xor_ipad[128];
13         unsigned char k_xor_opad[128];
14         unsigned char *catbuf;
15         int i;
16
17         if(sizeof(hashbuf) < (size_t) hlen)
18                 return false;
19         if(sizeof(k_xor_ipad) < (size_t) hblock)
20                 return false;
21         if(sizeof(k_xor_ipad) < (size_t) hlen)
22                 return false;
23
24         catbuf = (unsigned char *)Mem_Alloc(tempmempool, (size_t) hblock + max((size_t) hlen, (size_t) n));
25
26         if(k > hblock)
27         {
28                 // hash the key if it is too long
29                 hfunc(k_xor_opad, key, k);
30                 key = k_xor_opad;
31                 k = hlen;
32         }
33
34         if(k < hblock)
35         {
36                 // zero pad the key if it is too short
37                 if(key != k_xor_opad)
38                         memcpy(k_xor_opad, key, k);
39                 for(i = k; i < hblock; ++i)
40                         k_xor_opad[i] = 0;
41                 key = k_xor_opad;
42                 k = hblock;
43         }
44
45         for(i = 0; i < hblock; ++i)
46         {
47                 k_xor_ipad[i] = key[i] ^ 0x36;
48                 k_xor_opad[i] = key[i] ^ 0x5c;
49         }
50
51         memcpy(catbuf, k_xor_ipad, hblock);
52         memcpy(catbuf + hblock, in, n);
53         hfunc(hashbuf, catbuf, hblock + n);
54         memcpy(catbuf, k_xor_opad, hblock);
55         memcpy(catbuf + hblock, hashbuf, hlen);
56         hfunc(out, catbuf, hblock + hlen);
57
58         Mem_Free(catbuf);
59
60         return true;
61 }