-
Notifications
You must be signed in to change notification settings - Fork 1
/
hmac_sha256.c
87 lines (75 loc) · 2.45 KB
/
hmac_sha256.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
#include <stdio.h>
#include <stddef.h>
#include <stdint.h>
//#include "hmac_sha256.h"
//#include "sha256.h"
#include "sha256.c"
#define B 64
#define HMAC_SHA256_DIGEST_SIZE 32 /* Same as SHA-256's output size. */
#define SHA256_DIGEST_SIZE 32
#define L (SHA256_DIGEST_SIZE)
#define K (SHA256_DIGEST_SIZE * 2)
//typedef unsigned char uint8_t;
#define I_PAD 0x36
#define O_PAD 0x5C
void
hmac_sha256 (uint8_t out[HMAC_SHA256_DIGEST_SIZE],
const uint8_t *data, size_t data_len,
const uint8_t *key, size_t key_len)
{
// api_check_return (out);
// api_check_return (data);
// api_check_return (key);
// api_check_return (key_len <= B);
SHA256_CTX ss;
uint8_t kh[SHA256_DIGEST_SIZE];
/*
* If the key length is bigger than the buffer size B, apply the hash
* function to it first and use the result instead.
*/
if (key_len > B) {
sha256_init (&ss);
sha256_update (&ss, key, key_len);
sha256_final (&ss, kh);
key_len = SHA256_DIGEST_SIZE;
key = kh;
}
/*
* (1) append zeros to the end of K to create a B byte string
* (e.g., if K is of length 20 bytes and B=64, then K will be
* appended with 44 zero bytes 0x00)
* (2) XOR (bitwise exclusive-OR) the B byte string computed in step
* (1) with ipad
*/
uint8_t kx[B];
size_t i=0;
for (i = 0; i < key_len; i++) kx[i] = I_PAD ^ key[i];
for (i = key_len; i < B; i++) kx[i] = I_PAD ^ 0;
/*
* (3) append the stream of data 'text' to the B byte string resulting
* from step (2)
* (4) apply H to the stream generated in step (3)
*/
sha256_init (&ss);
sha256_update (&ss, kx, B);
sha256_update (&ss, data, data_len);
sha256_final (&ss, out);
/*
* (5) XOR (bitwise exclusive-OR) the B byte string computed in
* step (1) with opad
*
* NOTE: The "kx" variable is reused.
*/
for (i = 0; i < key_len; i++) kx[i] = O_PAD ^ key[i];
for (i = key_len; i < B; i++) kx[i] = O_PAD ^ 0;
/*
* (6) append the H result from step (4) to the B byte string
* resulting from step (5)
* (7) apply H to the stream generated in step (6) and output
* the result
*/
sha256_init (&ss);
sha256_update (&ss, kx, B);
sha256_update (&ss, out, SHA256_DIGEST_SIZE);
sha256_final (&ss, out);
}