| 1 |
/* |
| 2 |
* Copyright (C) 2014 Red Hat, Inc. |
| 3 |
* SPDX-License-Identifier: LGPL-2.1-or-later |
| 4 |
*/ |
| 5 |
|
| 6 |
#include "config.h" |
| 7 |
|
| 8 |
#include "cockpithex.h" |
| 9 |
|
| 10 |
#include "cockpitmemory.h" |
| 11 |
|
| 12 |
#include <assert.h> |
| 13 |
#include <stdint.h> |
| 14 |
#include <string.h> |
| 15 |
|
| 16 |
static const char HEX[] = "0123456789abcdef"; |
| 17 |
|
| 18 |
char * |
| 19 |
cockpit_hex_encode (const void * data, |
| 20 |
ssize_t length) |
| 21 |
{ |
| 22 |
const unsigned char *in = data; |
| 23 |
char *out; |
| 24 |
size_t i; |
| 25 |
|
| 26 |
if (length < 0) |
| 27 |
length = strlen (data); |
| 28 |
|
| 29 |
/* Check for overflow: length * 2 + 1 must fit in size_t */ |
| 30 |
assert (length <= (SIZE_MAX - 1) / 2); |
| 31 |
|
| 32 |
out = mallocx (length * 2 + 1); |
| 33 |
for (i = 0; i < length; i++) |
| 34 |
{ |
| 35 |
out[i * 2] = HEX[in[i] >> 4]; |
| 36 |
out[i * 2 + 1] = HEX[in[i] & 0xf]; |
| 37 |
} |
| 38 |
out[i * 2] = '\0'; |
| 39 |
return out; |
| 40 |
} |