1 /* Copyright (c) 2011,2013, NORDUnet A/S */
2 /* See LICENSE for licensing information. */
9 #include <nettle/sha.h>
10 #include <nettle/hmac.h>
11 #include "fticks_hashmac.h"
13 /** \a HASH is an input buffer of length SHA256_DIGEST_SIZE bytes.
14 \a OUT_LEN is the size in bytes of \OUT.
15 \a OUT is an output buffer of length \a OUT_LEN. */
17 _format_hash(const uint8_t *hash, size_t out_len, uint8_t *out)
22 memset(out, 0, out_len);
26 for (ir = 0, iw = 0; iw <= out_len - 3; ir++, iw += 2)
27 sprintf((char *) out + iw, "%02x", hash[ir % SHA256_DIGEST_SIZE]);
31 _hash(const uint8_t *in,
37 struct sha256_ctx ctx;
38 uint8_t hash[SHA256_DIGEST_SIZE];
41 sha256_update(&ctx, strlen((char *) in), in);
42 sha256_digest(&ctx, sizeof(hash), hash);
43 _format_hash(hash, out_len, out);
46 struct hmac_sha256_ctx ctx;
47 uint8_t hash[SHA256_DIGEST_SIZE];
49 hmac_sha256_set_key(&ctx, strlen((char *) key), key);
50 hmac_sha256_update(&ctx, strlen((char *) in), in);
51 hmac_sha256_digest(&ctx, sizeof(hash), hash);
52 _format_hash(hash, out_len, out);
56 /** Hash the Ethernet MAC address in \a IN, keying a HMAC with \a KEY
57 unless \a KEY is NULL. If \a KEY is null \a IN is hashed with an
58 ordinary cryptographic hash function such as SHA-2.
60 \a IN and \a KEY are NULL terminated strings.
62 \a IN is supposed to be an Ethernet MAC address and is sanitised
63 by lowercasing it, removing all but [0-9a-f] and truncating it at
64 the first ';' found. The truncation is done because RADIUS
65 supposedly has a praxis of tacking on SSID to the MAC address in
68 The resulting hash value is written to \a OUT as a NUL terminated
69 string of numbers in two-digit hexadecimal ASCII representation.
71 Exactly \a OUT_LEN bytes are written to \a OUT, based on the first
72 (\a OUT_LEN - 1) / 2 bytes of the hash. Note that in the case when
73 \OUT_LEN - 1 is more than two times the length of the hash, the
74 output is repeated by concatinating another hex ASCII
75 representation of the hash to the output until the buffer is full.
77 \return 0 on success, -ENOMEM on out of memory.
80 fticks_hashmac(const uint8_t *in,
85 uint8_t *in_copy = NULL;
89 in_copy = calloc(1, strlen((const char *) in) + 1);
93 /* Sanitise and lowercase 'in' into 'in_copy'. */
94 for (i = 0, p = in_copy; in[i] != '\0'; i++) {
99 if (in[i] >= '0' && in[i] <= '9') {
102 else if (tolower(in[i]) >= 'a' && tolower(in[i]) <= 'f') {
103 *p++ = tolower(in[i]);
107 _hash(in_copy, key, out_len, out);