-
Notifications
You must be signed in to change notification settings - Fork 0
/
hmac.c
106 lines (83 loc) · 2.54 KB
/
hmac.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/*
libpwsafe - a portable implementation of the passwordsafe format
Copyright © 2011 Noa Resare
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <string.h>
#include "sph_sha2.h"
#include "hmac.h"
#ifdef TEST
#include <stdio.h>
#endif
/* block size in bytes of SHA256 */
#define BLOCK_SIZE 64
/* hash output size in bytes for SHA256 */
#define HASH_SIZE 32
/**
* Initialize the HMAC state stucture
*/
void hmac_init(hmac_state *state, unsigned char *key, int key_length)
{
unsigned char tmp[BLOCK_SIZE] = {0};
int i;
sph_sha256_context c;
if (key_length > BLOCK_SIZE) {
sph_sha256_init(&c);
sph_sha256(&c, key, key_length);
sph_sha256_close(&c, tmp);
} else {
memcpy(tmp, key, key_length);
}
sph_sha256_init(&state->inner);
sph_sha256_init(&state->outer);
for (i = 0; i < BLOCK_SIZE; i++) {
tmp[i] = tmp[i] ^ 0x36;
}
sph_sha256(&state->inner, tmp, BLOCK_SIZE);
for (i = 0; i < BLOCK_SIZE; i++) {
tmp[i] = tmp[i] ^ (0x36 ^ 0x5c);
}
sph_sha256(&state->outer, tmp, BLOCK_SIZE);
}
void hmac_update(hmac_state *state, unsigned char *data, int count)
{
sph_sha256(&state->inner, data, count);
}
void hmac_result(hmac_state *state, unsigned char *result)
{
unsigned char tmp[32];
sph_sha256_close(&state->inner, tmp);
sph_sha256(&state->outer, tmp, 32);
sph_sha256_close(&state->outer, result);
}
#ifdef TEST
static void print_hex(unsigned char *data, int len)
{
int i;
for (i = 0; i < len; i++) {
printf("%02hhx ", data[i]);
}
printf("\n");
}
int main(int argc, char **argv)
{
unsigned char result[32];
hmac_state state;
char *key = "key";
char *data = "The quick brown fox jumps over the lazy dog";
hmac_init(&state, (unsigned char*)key, strlen(key));
hmac_update(&state, (unsigned char*)data, strlen(data));
hmac_result(&state, result);
print_hex(result, 32);
return 0;
}
#endif