summaryrefslogtreecommitdiff
path: root/fticks.c
blob: ab750a3be9cff7cc9f8ce2664126e2619b1a65c5 (plain)
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
/* Copyright (C) 2011 NORDUnet A/S
 * See LICENSE for information about licensing.
 */

#include <stdio.h>		/* For sprintf().  */
#include <string.h>
#include <nettle/sha.h>
#include <nettle/hmac.h>

static void
format_hash(const uint8_t *hash, size_t out_len, uint8_t *out)
{
    int i;

    for (i = 0; i < out_len / 2; i++)
	sprintf((char *) out + i*2, "%02x", hash[i % SHA256_DIGEST_SIZE]);
}

static void
hash(const uint8_t *in,
     const uint8_t *key,
     size_t out_len,
     uint8_t *out)
{
    if (key == NULL) {
	struct sha256_ctx ctx;
	uint8_t hash[SHA256_DIGEST_SIZE];

	sha256_init(&ctx);
	sha256_update(&ctx, strlen((char *) in), in);
	sha256_digest(&ctx, sizeof(hash), hash);
	format_hash(hash, out_len, out);
    }
    else {
	struct hmac_sha256_ctx ctx;
	uint8_t hash[SHA256_DIGEST_SIZE];

	hmac_sha256_set_key(&ctx, strlen((char *) key), key);
	hmac_sha256_update(&ctx, strlen((char *) in), in);
	hmac_sha256_digest(&ctx, sizeof(hash), hash);
	format_hash(hash, out_len, out);
    }
}

/** Hash the MAC in \a IN, keying with \a KEY if it's not NULL.

    \a IN and \a KEY are NULL terminated strings.

    \a IN is sanitised by lowercasing it, removing all but [0-9a-f]
    and truncating it at first ';' (due to RADIUS praxis with tacking
    on SSID to MAC in Calling-Station-Id).  */
void
fticks_hashmac(const uint8_t *in,
	       const uint8_t *key,
	       size_t out_len,
	       uint8_t *out)
{
    /* TODO: lowercase */
    /* TODO: s/[!0-9a-f]//1 */
    /* TODO: truncate after first ';', if any */

    hash(in, key, out_len, out);
}

/* Local Variables: */
/* c-file-style: "stroustrup" */
/* End: */