Line data Source code
1 : /*
2 : Authors:
3 : Jakub Hrozek <jhrozek@redhat.com>
4 :
5 : Copyright (C) 2012 Red Hat
6 :
7 : This program is free software; you can redistribute it and/or modify
8 : it under the terms of the GNU General Public License as published by
9 : the Free Software Foundation; either version 3 of the License, or
10 : (at your option) any later version.
11 :
12 : This program is distributed in the hope that it will be useful,
13 : but WITHOUT ANY WARRANTY; without even the implied warranty of
14 : MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 : GNU General Public License for more details.
16 :
17 : You should have received a copy of the GNU General Public License
18 : along with this program. If not, see <http://www.gnu.org/licenses/>.
19 : */
20 :
21 : #include <talloc.h>
22 :
23 : #include "util/util.h"
24 : #include "util/crypto/nss/nss_util.h"
25 : #include "util/crypto/sss_crypto.h"
26 :
27 : #include <base64.h>
28 :
29 : /* NSS wraps b64 encoded buffers with CRLF automatically after 64 chars. This
30 : * function strips the CRLF double-chars. The buffer can be decoded with plain
31 : * NSS calls */
32 12 : char *sss_base64_encode(TALLOC_CTX *mem_ctx,
33 : const unsigned char *inbuf,
34 : size_t inbufsize)
35 : {
36 : int ret;
37 12 : char *b64encoded = NULL;
38 : int i, j, b64size;
39 : char *outbuf;
40 :
41 : /* initialize NSS if needed */
42 12 : ret = nspr_nss_init();
43 12 : if (ret != EOK) {
44 0 : return NULL;
45 : }
46 :
47 12 : b64encoded = BTOA_DataToAscii(inbuf, inbufsize);
48 12 : if (!b64encoded) return NULL;
49 :
50 12 : b64size = strlen(b64encoded) + 1;
51 12 : outbuf = talloc_array(mem_ctx, char, b64size);
52 12 : if (outbuf == NULL) {
53 0 : PORT_Free(b64encoded);
54 0 : return NULL;
55 : }
56 :
57 10340 : for (i=0, j=0; i < b64size; i++) {
58 10328 : if (b64encoded[i] == '\n' || b64encoded[i] == '\r') {
59 300 : continue;
60 : }
61 10028 : outbuf[j++] = b64encoded[i]; /* will also copy the trailing \0 char */
62 : }
63 :
64 12 : PORT_Free(b64encoded);
65 12 : return outbuf;
66 : }
67 :
68 28 : unsigned char *sss_base64_decode(TALLOC_CTX *mem_ctx,
69 : const char *inbuf,
70 : size_t *outbufsize)
71 : {
72 : int ret;
73 28 : unsigned char *b64decoded = NULL;
74 : unsigned int size;
75 : unsigned char *outbuf;
76 :
77 : /* initialize NSS if needed */
78 28 : ret = nspr_nss_init();
79 28 : if (ret != EOK) {
80 0 : return NULL;
81 : }
82 :
83 28 : b64decoded = ATOB_AsciiToData(inbuf, &size);
84 28 : if (!b64decoded) return NULL;
85 :
86 28 : outbuf = talloc_memdup(mem_ctx, b64decoded, size);
87 28 : PORT_Free(b64decoded);
88 28 : if (!outbuf) return NULL;
89 :
90 28 : *outbufsize = size;
91 28 : return outbuf;
92 : }
|