-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhmac.c
More file actions
58 lines (44 loc) · 2.07 KB
/
Copy pathhmac.c
File metadata and controls
58 lines (44 loc) · 2.07 KB
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
#include "hmac.h"
#include "scrypt.h"
#include <stdlib.h>
#include <string.h>
#include "errorhandling.h"
unsigned char* hmac(const unsigned char* key, const size_t keyLen, unsigned char* (*hash)(const unsigned char*, size_t),
const unsigned char* message, const size_t messageLen, int const blockSize, const size_t hashLen) {
unsigned char* blockSizedKey = computeBlockSizedKey(key, keyLen, hash, hashLen, blockSize);
if (blockSizedKey == NULL) return error_handler_null("Couldn't allocate memory for blockSizedKey in computeBlockSizedKey.", 0);
unsigned char* outerKeyPad = malloc(blockSize);
if (outerKeyPad == NULL) return error_handler_null("Couldn't allocate memory for outerKeyPad in HMAC.", 1, blockSizedKey);
unsigned char* innerKeyPad = malloc(blockSize);
if (innerKeyPad == NULL) return error_handler_null("Couldn't allocate memory for innerKeyPad in HMAC.", 2, outerKeyPad, blockSizedKey);
xor_constant(outerKeyPad, blockSizedKey, 0x5c, blockSize);
xor_constant(innerKeyPad, blockSizedKey, 0x36, blockSize);
unsigned char* innerInput = concat(innerKeyPad, blockSize, message, strlen((char*) message));
unsigned char* innerHash = hash(innerInput, blockSize + messageLen);
unsigned char* outerInput = concat(outerKeyPad, blockSize, innerHash, hashLen);
unsigned char* result = hash(outerInput, blockSize + hashLen);
free(blockSizedKey);
free(outerKeyPad);
free(innerKeyPad);
free(innerInput);
free(innerHash);
free(outerInput);
return result;
}
unsigned char* computeBlockSizedKey(const unsigned char* key, size_t keyLen, unsigned char* (*hash)(const unsigned char*, size_t), size_t const hashLen, int const blockSize) {
unsigned char* result;
if (keyLen > blockSize) {
result = hash(key, keyLen);
keyLen = hashLen;
}
else {
result = malloc(blockSize);
if (result == NULL)
return NULL;
memcpy(result, key, keyLen);
}
if (keyLen < blockSize) {
memset(result + keyLen, 0, blockSize - keyLen);
}
return result;
}