ApiToken.h
| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | #ifndef apitoken_h | ||
| 2 | #define apitoken_h | ||
| 3 | #include <stddef.h> | ||
| 4 | #include <stdint.h> | ||
| 5 | |||
| 6 | // The token key's size: 32 random bytes the device makes on first boot and | ||
| 7 | // keeps in NVS. It never leaves the device. | ||
| 8 | #define API_TOKEN_KEY_SIZE 32 | ||
| 9 | // A token's buffer: an HMAC-SHA256 in hex and its terminator. | ||
| 10 | #define API_TOKEN_SIZE 65 | ||
| 11 | |||
| 12 | // True when given is the expected token. It takes the same time whatever | ||
| 13 | // given holds, so the time doesn't tell how much of a guess was right. Only | ||
| 14 | // expected's length shows, and every token has the same one. An empty | ||
| 15 | // expected token, which is what a failed HMAC leaves, matches nothing. | ||
| 16 | 11 | inline bool tokenMatches(const char *expected, const char *given) { | |
| 17 | 11 | if(!expected || !given || !expected[0]) return false; | |
| 18 | 8 | uint8_t diff = 0; | |
| 19 | 520 | for(size_t i = 0; expected[i]; i++) { | |
| 20 | 512 | diff |= (uint8_t)(expected[i] ^ *given); | |
| 21 | // A shorter given compares its terminator with the rest of expected. | ||
| 22 | 512 | if(*given) given++; | |
| 23 | } | ||
| 24 | // A longer given doesn't match either. | ||
| 25 | 8 | diff |= (uint8_t)*given; | |
| 26 | 8 | return diff == 0; | |
| 27 | } | ||
| 28 | #endif | ||
| 29 |