Constant-time hex2bin.

This commit is contained in:
Frank Denis 2015-02-10 17:01:51 +01:00
parent 2fb83ade4c
commit f8af1790dd

View File

@ -131,22 +131,25 @@ sodium_hex2bin(unsigned char * const bin, const size_t bin_maxlen,
int ret = 0; int ret = 0;
unsigned char c; unsigned char c;
unsigned char c_acc = 0U; unsigned char c_acc = 0U;
unsigned char c_num; unsigned char c_alpha0, c_alpha;
unsigned char c_num0, c_num;
unsigned char c_val; unsigned char c_val;
unsigned char state = 0U; unsigned char state = 0U;
while (hex_pos < hex_len) { while (hex_pos < hex_len) {
c = (unsigned char) hex[hex_pos]; c = (unsigned char) hex[hex_pos];
if ((c_num = c ^ 48U) < 10U) { c_num = c ^ 48U;
c_val = c_num; c_num0 = (c_num - 10U) >> 8;
} else if ((c_num = (c & ~32U)) > 64 && c_num < 71U) { c_alpha = (c & ~32U) - 55U;
c_val = c_num - 55U; c_alpha0 = ((c_alpha - 10U) ^ (c_alpha - 16U)) >> 8;
} else if (ignore != NULL && strchr(ignore, c) != NULL && state == 0U) { if ((c_num0 | c_alpha0) == 0U) {
hex_pos++; if (ignore != NULL && state == 0U && strchr(ignore, c) != NULL) {
continue; hex_pos++;
} else { continue;
}
break; break;
} }
c_val = (c_num0 & c_num) | (c_alpha0 & c_alpha);
if (bin_pos >= bin_maxlen) { if (bin_pos >= bin_maxlen) {
ret = -1; ret = -1;
errno = ERANGE; errno = ERANGE;