1
mirror of https://github.com/jedisct1/libsodium.git synced 2024-12-24 12:36:01 -07:00

Add a sodium_bin2hex utility function.

This commit is contained in:
Frank Denis 2013-07-07 23:38:14 -07:00
parent a6490db658
commit 1a3786705e
5 changed files with 42 additions and 7 deletions

View File

@ -135,11 +135,17 @@ Warning: if a region has been allocated on the heap, you still have
to make sure that it can't get swapped to disk, possibly using
`mlock(2)`.
In order to compare memory zones in constant time, Sodium proides:
In order to compare memory zones in constant time, Sodium provides:
int sodium_memcmp(const void * const b1_, const void * const b2_,
size_t size);
And a convenience function for converting a binary buffer to a
hexadecimal string:
char * sodium_bin2hex(char * const hex, const size_t hexlen,
const unsigned char *bin, const size_t binlen);
## New operations
### crypto_shorthash

View File

@ -25,6 +25,10 @@ void sodium_memzero(void * const pnt, const size_t len);
SODIUM_EXPORT
int sodium_memcmp(const void * const b1_, const void * const b2_, size_t size);
SODIUM_EXPORT
char *sodium_bin2hex(char * const hex, const size_t hexlen,
const unsigned char *bin, const size_t binlen);
#ifdef __cplusplus
}
#endif

View File

@ -63,3 +63,24 @@ _sodium_alignedcalloc(unsigned char ** const unaligned_p, const size_t len)
return aligned;
}
char *
sodium_bin2hex(char * const hex, const size_t hexlen,
const unsigned char *bin, const size_t binlen)
{
static const char hexdigits[16] = "0123456789abcdef";
size_t i = (size_t) 0U;
size_t j = (size_t) 0U;
if (binlen >= SIZE_MAX / 2 || hexlen < binlen * 2U) {
abort();
}
while (i < binlen) {
hex[j++] = hexdigits[bin[i] >> 4];
hex[j++] = hexdigits[bin[i] & 0xf];
i++;
}
hex[j] = 0;
return hex;
}

View File

@ -8,17 +8,20 @@ int main(void)
{
unsigned char buf1[1000];
unsigned char buf2[1000];
char buf3[33];
randombytes(buf1, sizeof buf1);
memcpy(buf2, buf1, sizeof buf2);
printf ("%d\n", sodium_memcmp(buf1, buf2, sizeof buf1));
printf("%d\n", sodium_memcmp(buf1, buf2, sizeof buf1));
sodium_memzero(buf1, 0U);
printf ("%d\n", sodium_memcmp(buf1, buf2, sizeof buf1));
printf("%d\n", sodium_memcmp(buf1, buf2, sizeof buf1));
sodium_memzero(buf1, sizeof buf1 / 2);
printf ("%d\n", sodium_memcmp(buf1, buf2, sizeof buf1));
printf ("%d\n", sodium_memcmp(buf1, buf2, 0U));
printf("%d\n", sodium_memcmp(buf1, buf2, sizeof buf1));
printf("%d\n", sodium_memcmp(buf1, buf2, 0U));
sodium_memzero(buf2, sizeof buf2 / 2);
printf ("%d\n", sodium_memcmp(buf1, buf2, sizeof buf1));
printf("%d\n", sodium_memcmp(buf1, buf2, sizeof buf1));
printf("%s\n", sodium_bin2hex(buf3, 33U,
(const unsigned char *)
"0123456789ABCDEF", 16U));
return 0;
}

View File

@ -3,3 +3,4 @@
255
0
0
30313233343536373839414243444546