]> git.xonotic.org Git - xonotic/darkplaces.git/blob - hmac.c
Add my own HMAC implementation (verified using the test vectors). Planning to use...
[xonotic/darkplaces.git] / hmac.c
1 #include "quakedef.h"
2 #include "hmac.h"
3
4 void hmac(
5         hashfunc_t hfunc, int hlen, int hblock,
6         unsigned char *out,
7         unsigned char *in, int n,
8         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[256];
15         int i;
16
17         if(sizeof(hashbuf) < (size_t) hlen)
18                 Host_Error("Invalid hash function used for HMAC - too long hash length");
19         if(sizeof(k_xor_ipad) < (size_t) hblock)
20                 Host_Error("Invalid hash function used for HMAC - too long hash block length");
21         if(sizeof(catbuf) < (size_t) hblock + (size_t) hlen)
22                 Host_Error("Invalid hash function used for HMAC - too long hash block length");
23         if(sizeof(catbuf) < (size_t) hblock + (size_t) n)
24                 Host_Error("Invalid hash function used for HMAC - too long message length");
25
26         if(k > hblock)
27         {
28                 // hash the key if it is too long
29                 // NO! that makes it too short if hblock != hlen
30                 // just shorten it, then
31                 // hfunc(hashbuf, key, k);
32                 // key = hashbuf;
33                 k = hblock;
34         }
35         else if(k < hblock)
36         {
37                 // zero pad the key if it is too short
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 }