| 1 | /* convert.c - Hex conversion functions. |
| 2 | * Copyright (C) 2006, 2008 Free Software Foundation, Inc. |
| 3 | * |
| 4 | * This file is part of GnuPG. |
| 5 | * |
| 6 | * GnuPG is free software; you can redistribute it and/or modify |
| 7 | * it under the terms of the GNU General Public License as published by |
| 8 | * the Free Software Foundation; either version 3 of the License, or |
| 9 | * (at your option) any later version. |
| 10 | * |
| 11 | * GnuPG is distributed in the hope that it will be useful, |
| 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 14 | * GNU General Public License for more details. |
| 15 | * |
| 16 | * You should have received a copy of the GNU General Public License |
| 17 | * along with this program; if not, see <http://www.gnu.org/licenses/>. |
| 18 | */ |
| 19 | |
| 20 | #include <util-local.h> |
| 21 | |
| 22 | #include <stdlib.h> |
| 23 | #include <errno.h> |
| 24 | #include <ctype.h> |
| 25 | |
| 26 | #include "util.h" |
| 27 | |
| 28 | |
| 29 | #define tohex(n) ((n) < 10 ? ((n) + '0') : (((n) - 10) + 'A')) |
| 30 | |
| 31 | static char * |
| 32 | do_bin2hex (const void *buffer, size_t length, char *stringbuf, int with_colon) |
| 33 | { |
| 34 | const unsigned char *s; |
| 35 | char *p; |
| 36 | |
| 37 | if (!stringbuf) |
| 38 | { |
| 39 | /* Not really correct for with_colon but we don't care about the |
| 40 | one wasted byte. */ |
| 41 | size_t n = with_colon? 3:2; |
| 42 | size_t nbytes = n * length + 1; |
| 43 | if (length && (nbytes-1) / n != length) |
| 44 | { |
| 45 | errno = ENOMEM; |
| 46 | return NULL; |
| 47 | } |
| 48 | stringbuf = xtrymalloc (nbytes); |
| 49 | if (!stringbuf) |
| 50 | return NULL; |
| 51 | } |
| 52 | |
| 53 | for (s = buffer, p = stringbuf; length; length--, s++) |
| 54 | { |
| 55 | if (with_colon && s != buffer) |
| 56 | *p++ = ':'; |
| 57 | *p++ = tohex ((*s>>4)&15); |
| 58 | *p++ = tohex (*s&15); |
| 59 | } |
| 60 | *p = 0; |
| 61 | |
| 62 | return stringbuf; |
| 63 | } |
| 64 | |
| 65 | |
| 66 | /* Convert LENGTH bytes of data in BUFFER into hex encoding and store |
| 67 | that at the provided STRINGBUF. STRINGBUF must be allocated of at |
| 68 | least (2*LENGTH+1) bytes or be NULL so that the function mallocs an |
| 69 | appropriate buffer. Returns STRINGBUF or NULL on error (which may |
| 70 | only occur if STRINGBUF has been NULL and the internal malloc |
| 71 | failed). */ |
| 72 | char * |
| 73 | bin2hex (const void *buffer, size_t length, char *stringbuf) |
| 74 | { |
| 75 | return do_bin2hex (buffer, length, stringbuf, 0); |
| 76 | } |