/* This software was written by Dirk Engling It is considered beerware. Prost. Skol. Cheers or whatever. $id$ */ /* System */ #include #include /* Opentracker */ #include "ot_hex.h" static int fromhex(unsigned char c) { if (c >= '0' && c <= '9') return c - '0'; c |= 0x20; /* fold upper case onto lower, digits are already handled */ if (c >= 'a' && c <= 'f') return c - 'a' + 10; return -1; } int hex_isdigit(int c) { return fromhex((unsigned char)c) >= 0; } char *hex_fromhash(char *dest, const uint8_t *hash) { static const char digits[] = "0123456789ABCDEF"; char *d = dest; size_t i; for (i = 0; i < sizeof(ot_hash); ++i) { *d++ = digits[hash[i] >> 4]; *d++ = digits[hash[i] & 15]; } *d = 0; return dest; } int hex_tohash(ot_hash hash, const char *src) { uint8_t decoded[sizeof(ot_hash)]; size_t i; for (i = 0; i < sizeof(ot_hash); ++i) { int high, low; /* Tested one character at a time so that a string ending early stops us at its terminator rather than one byte past it */ if ((high = fromhex((unsigned char)src[2 * i])) < 0) return 0; if ((low = fromhex((unsigned char)src[2 * i + 1])) < 0) return 0; decoded[i] = (uint8_t)((high << 4) | low); } memcpy(hash, decoded, sizeof(decoded)); return 1; }