1 /* Copyright (c) 2011, NORDUnet A/S */
2 /* See LICENSE for licensing information. */
9 #include <nettle/sha.h>
10 #include <nettle/hmac.h>
11 #include "fticks_hashmac.h"
14 _format_hash(const uint8_t *hash, size_t out_len, uint8_t *out)
18 for (ir = 0, iw = 0; iw <= out_len - 3; ir++, iw += 2)
19 sprintf((char *) out + iw, "%02x", hash[ir % SHA256_DIGEST_SIZE]);
23 _hash(const uint8_t *in,
29 struct sha256_ctx ctx;
30 uint8_t hash[SHA256_DIGEST_SIZE];
33 sha256_update(&ctx, strlen((char *) in), in);
34 sha256_digest(&ctx, sizeof(hash), hash);
35 _format_hash(hash, out_len, out);
38 struct hmac_sha256_ctx ctx;
39 uint8_t hash[SHA256_DIGEST_SIZE];
41 hmac_sha256_set_key(&ctx, strlen((char *) key), key);
42 hmac_sha256_update(&ctx, strlen((char *) in), in);
43 hmac_sha256_digest(&ctx, sizeof(hash), hash);
44 _format_hash(hash, out_len, out);
48 /** Hash the Ethernet MAC address in \a IN, keying a HMAC with \a KEY
49 unless \a KEY is NULL. If \a KEY is null \a IN is hashed with an
50 ordinary cryptographic hash function such as SHA-2.
52 \a IN and \a KEY are NULL terminated strings.
54 \a IN is supposed to be an Ethernet MAC address and is sanitised
55 by lowercasing it, removing all but [0-9a-f] and truncating it at
56 the first ';' found. The truncation is done because RADIUS
57 supposedly has a praxis of tacking on SSID to the MAC address in
60 \return 0 on success, -ENOMEM on out of memory.
63 fticks_hashmac(const uint8_t *in,
68 uint8_t *in_copy = NULL;
72 in_copy = calloc(1, strlen((const char *) in) + 1);
76 /* Sanitise and lowercase 'in' into 'in_copy'. */
77 for (i = 0, p = in_copy; in[i] != '\0'; i++) {
82 if (in[i] >= '0' && in[i] <= '9') {
85 else if (tolower(in[i]) >= 'a' && tolower(in[i]) <= 'f') {
86 *p++ = tolower(in[i]);
90 _hash(in_copy, key, out_len, out);