Browse Source

Add a helper function to check a hex string is valid

master
Con Kolivas 10 years ago
parent
commit
e5b9e84129
  1. 26
      src/libckpool.c
  2. 4
      src/libckpool.h

26
src/libckpool.c

@ -1,5 +1,5 @@
/* /*
* Copyright 2014 Con Kolivas * Copyright 2014-2015 Con Kolivas
* *
* This program is free software; you can redistribute it and/or modify it * This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free * under the terms of the GNU General Public License as published by the Free
@ -1351,6 +1351,30 @@ const int hex2bin_tbl[256] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
}; };
bool _validhex(const char *buf, const char *file, const char *func, const int line)
{
unsigned int i, slen;
bool ret = false;
slen = strlen(buf);
if (!slen || slen % 2) {
LOGDEBUG("Invalid hex due to length %u from %s %s:%d", slen, file, func, line);
goto out;
}
for (i = 0; i < slen; i++) {
uchar idx = buf[i];
if (hex2bin_tbl[idx] == -1) {
LOGDEBUG("Invalid hex due to value %u at offset %d from %s %s:%d",
idx, i, file, func, line);
goto out;
}
}
ret = true;
out:
return ret;
}
/* Does the reverse of bin2hex but does not allocate any ram */ /* Does the reverse of bin2hex but does not allocate any ram */
bool _hex2bin(void *vp, const void *vhexstr, size_t len, const char *file, const char *func, const int line) bool _hex2bin(void *vp, const void *vhexstr, size_t len, const char *file, const char *func, const int line)
{ {

4
src/libckpool.h

@ -1,5 +1,5 @@
/* /*
* Copyright 2014 Con Kolivas * Copyright 2014-2015 Con Kolivas
* *
* This program is free software; you can redistribute it and/or modify it * This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free * under the terms of the GNU General Public License as published by the Free
@ -495,6 +495,8 @@ void _dealloc(void **ptr);
extern const int hex2bin_tbl[]; extern const int hex2bin_tbl[];
void __bin2hex(void *vs, const void *vp, size_t len); void __bin2hex(void *vs, const void *vp, size_t len);
void *bin2hex(const void *vp, size_t len); void *bin2hex(const void *vp, size_t len);
bool _validhex(const char *buf, const char *file, const char *func, const int line);
#define validhex(buf) _validhex(buf, __FILE__, __func__, __LINE__)
bool _hex2bin(void *p, const void *vhexstr, size_t len, const char *file, const char *func, const int line); bool _hex2bin(void *p, const void *vhexstr, size_t len, const char *file, const char *func, const int line);
#define hex2bin(p, vhexstr, len) _hex2bin(p, vhexstr, len, __FILE__, __func__, __LINE__) #define hex2bin(p, vhexstr, len) _hex2bin(p, vhexstr, len, __FILE__, __func__, __LINE__)
char *http_base64(const char *src); char *http_base64(const char *src);

Loading…
Cancel
Save