From c7919a4fe41133cc466aa3d9431bfceee5784e7b Mon Sep 17 00:00:00 2001 From: Jan Cholasta Date: Fri, 3 Feb 2012 22:10:17 +0100 Subject: UTIL: Provide base64 encoding and decoding functions --- src/util/crypto/nss/nss_base64.c | 91 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 src/util/crypto/nss/nss_base64.c (limited to 'src/util/crypto/nss/nss_base64.c') diff --git a/src/util/crypto/nss/nss_base64.c b/src/util/crypto/nss/nss_base64.c new file mode 100644 index 00000000..be3de487 --- /dev/null +++ b/src/util/crypto/nss/nss_base64.c @@ -0,0 +1,91 @@ +/* + Authors: + Jakub Hrozek + + Copyright (C) 2012 Red Hat + + 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 Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#include + +#include "util/util.h" +#include "util/crypto/nss/nss_util.h" + +#include + +/* NSS wraps b64 encoded buffers with CRLF automatically after 64 chars. This + * function strips the CRLF double-chars. The buffer can be decoded with plain + * NSS calls */ +char *sss_base64_encode(TALLOC_CTX *mem_ctx, + const unsigned char *inbuf, + size_t inbufsize) +{ + int ret; + char *b64encoded = NULL; + int i, j, b64size; + char *outbuf; + + /* initialize NSS if needed */ + ret = nspr_nss_init(); + if (ret != EOK) { + return NULL; + } + + b64encoded = BTOA_DataToAscii(inbuf, inbufsize); + if (!b64encoded) return NULL; + + b64size = strlen(b64encoded) + 1; + outbuf = talloc_array(mem_ctx, char, b64size); + if (outbuf == NULL) { + PORT_Free(b64encoded); + return NULL; + } + + for (i=0, j=0; i < b64size; i++) { + if (b64encoded[i] == '\n' || b64encoded[i] == '\r') { + continue; + } + outbuf[j++] = b64encoded[i]; /* will also copy the trailing \0 char */ + } + + PORT_Free(b64encoded); + return outbuf; +} + +unsigned char *sss_base64_decode(TALLOC_CTX *mem_ctx, + const char *inbuf, + size_t *outbufsize) +{ + int ret; + unsigned char *b64decoded = NULL; + unsigned int size; + unsigned char *outbuf; + + /* initialize NSS if needed */ + ret = nspr_nss_init(); + if (ret != EOK) { + return NULL; + } + + b64decoded = ATOB_AsciiToData(inbuf, &size); + if (!b64decoded) return NULL; + + outbuf = talloc_memdup(mem_ctx, b64decoded, size); + PORT_Free(b64decoded); + if (!outbuf) return NULL; + + *outbufsize = size; + return outbuf; +} -- cgit