1 /* 2 * QEMU base64 helpers 3 * 4 * Copyright (c) 2015 Red Hat, Inc. 5 * 6 * This library is free software; you can redistribute it and/or 7 * modify it under the terms of the GNU Lesser General Public 8 * License as published by the Free Software Foundation; either 9 * version 2 of the License, or (at your option) any later version. 10 * 11 * This library 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 GNU 14 * Lesser General Public License for more details. 15 * 16 * You should have received a copy of the GNU Lesser General Public 17 * License along with this library; if not, see <http://www.gnu.org/licenses/>. 18 * 19 */ 20 21 #include "qemu/osdep.h" 22 #include "qemu/base64.h" 23 24 static const char *base64_valid_chars = 25 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n"; 26 27 uint8_t *qbase64_decode(const char *input, 28 size_t in_len, 29 size_t *out_len, 30 Error **errp) 31 { 32 *out_len = 0; 33 34 if (in_len != -1) { 35 /* Lack of NUL terminator is an error */ 36 if (input[in_len] != '\0') { 37 error_setg(errp, "Base64 data is not NUL terminated"); 38 return NULL; 39 } 40 /* Check there's no NULs embedded since we expect 41 * this to be valid base64 data */ 42 if (memchr(input, '\0', in_len) != NULL) { 43 error_setg(errp, "Base64 data contains embedded NUL characters"); 44 return NULL; 45 } 46 47 /* Now we know its a valid nul terminated string 48 * strspn is safe to use... */ 49 } else { 50 in_len = strlen(input); 51 } 52 53 if (strspn(input, base64_valid_chars) != in_len) { 54 error_setg(errp, "Base64 data contains invalid characters"); 55 return NULL; 56 } 57 58 return g_base64_decode(input, out_len); 59 } 60