1 /* Copyright (C) 2011 NORDUnet A/S
2 * See LICENSE for information about licensing.
10 #include <nettle/sha.h>
11 #include <nettle/hmac.h>
12 #include "fticks_hashmac.h"
15 _format_hash(const uint8_t *hash, size_t out_len, uint8_t *out)
19 for (ir = 0, iw = 0; iw <= out_len - 3; ir++, iw += 2)
20 sprintf((char *) out + iw, "%02x", hash[ir % SHA256_DIGEST_SIZE]);
24 _hash(const uint8_t *in,
30 struct sha256_ctx ctx;
31 uint8_t hash[SHA256_DIGEST_SIZE];
34 sha256_update(&ctx, strlen((char *) in), in);
35 sha256_digest(&ctx, sizeof(hash), hash);
36 _format_hash(hash, out_len, out);
39 struct hmac_sha256_ctx ctx;
40 uint8_t hash[SHA256_DIGEST_SIZE];
42 hmac_sha256_set_key(&ctx, strlen((char *) key), key);
43 hmac_sha256_update(&ctx, strlen((char *) in), in);
44 hmac_sha256_digest(&ctx, sizeof(hash), hash);
45 _format_hash(hash, out_len, out);
49 /** Hash the Ethernet MAC address in \a IN, keying a HMAC with \a KEY
50 unless \a KEY is NULL. If \a KEY is null \a IN is hashed with an
51 ordinary cryptographic hash function such as SHA-2.
53 \a IN and \a KEY are NULL terminated strings.
55 \a IN is supposed to be an Ethernet MAC address and is sanitised
56 by lowercasing it, removing all but [0-9a-f] and truncating it at
57 the first ';' found. The truncation is done because RADIUS
58 supposedly has a praxis of tacking on SSID to the MAC address in
61 \return 0 on success, -ENOMEM on out of memory.
64 fticks_hashmac(const uint8_t *in,
69 uint8_t *in_copy = NULL;
73 in_copy = calloc(1, strlen((const char *) in) + 1);
77 /* Sanitise and lowercase 'in' into 'in_copy'. */
78 for (i = 0, p = in_copy; in[i] != '\0'; i++) {
83 if (in[i] >= '0' && in[i] <= '9') {
86 else if (tolower(in[i]) >= 'a' && tolower(in[i]) <= 'f') {
87 *p++ = tolower(in[i]);
91 _hash(in_copy, key, out_len, out);