6 #include <nettle/sha.h>
7 #include <nettle/hmac.h>
8 #include "fticks_hashmac.h"
11 _format_hash(const uint8_t *hash, size_t out_len, uint8_t *out)
15 for (ir = 0, iw = 0; iw <= out_len - 3; ir++, iw += 2)
16 sprintf((char *) out + iw, "%02x", hash[ir % SHA256_DIGEST_SIZE]);
20 _hash(const uint8_t *in,
26 struct sha256_ctx ctx;
27 uint8_t hash[SHA256_DIGEST_SIZE];
30 sha256_update(&ctx, strlen((char *) in), in);
31 sha256_digest(&ctx, sizeof(hash), hash);
32 _format_hash(hash, out_len, out);
35 struct hmac_sha256_ctx ctx;
36 uint8_t hash[SHA256_DIGEST_SIZE];
38 hmac_sha256_set_key(&ctx, strlen((char *) key), key);
39 hmac_sha256_update(&ctx, strlen((char *) in), in);
40 hmac_sha256_digest(&ctx, sizeof(hash), hash);
41 _format_hash(hash, out_len, out);
45 /** Hash the Ethernet MAC address in \a IN, keying a HMAC with \a KEY
46 unless \a KEY is NULL. If \a KEY is null \a IN is hashed with an
47 ordinary cryptographic hash function such as SHA-2.
49 \a IN and \a KEY are NULL terminated strings.
51 \a IN is supposed to be an Ethernet MAC address and is sanitised
52 by lowercasing it, removing all but [0-9a-f] and truncating it at
53 the first ';' found. The truncation is done because RADIUS
54 supposedly has a praxis of tacking on SSID to the MAC address in
57 \return 0 on success, -ENOMEM on out of memory.
60 fticks_hashmac(const uint8_t *in,
65 uint8_t *in_copy = NULL;
69 in_copy = calloc(1, strlen((const char *) in) + 1);
73 /* Sanitise and lowercase 'in' into 'in_copy'. */
74 for (i = 0, p = in_copy; in[i] != '\0'; i++) {
79 if (in[i] >= '0' && in[i] <= '9') {
82 else if (tolower(in[i]) >= 'a' && tolower(in[i]) <= 'f') {
83 *p++ = tolower(in[i]);
87 _hash(in_copy, key, out_len, out);