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 13 : char *sss_base64_encode(TALLOC_CTX *mem_ctx,
33 : const unsigned char *inbuf,
34 : size_t inbufsize)
35 : {
36 : int ret;
37 13 : char *b64encoded = NULL;
38 : int i, j, b64size;
39 : char *outbuf;
40 :
41 : /* initialize NSS if needed */
42 13 : ret = nspr_nss_init();
43 13 : if (ret != EOK) {
44 0 : return NULL;
45 : }
46 :
47 13 : b64encoded = BTOA_DataToAscii(inbuf, inbufsize);
48 13 : if (!b64encoded) return NULL;
49 :
50 13 : b64size = strlen(b64encoded) + 1;
51 13 : outbuf = talloc_array(mem_ctx, char, b64size);
52 13 : if (outbuf == NULL) {
53 0 : PORT_Free(b64encoded);
54 0 : return NULL;
55 : }
56 :
57 11768 : for (i=0, j=0; i < b64size; i++) {
58 11755 : if (b64encoded[i] == '\n' || b64encoded[i] == '\r') {
59 342 : continue;
60 : }
61 11413 : outbuf[j++] = b64encoded[i]; /* will also copy the trailing \0 char */
62 : }
63 :
64 13 : PORT_Free(b64encoded);
65 13 : return outbuf;
66 : }
67 :
68 43 : unsigned char *sss_base64_decode(TALLOC_CTX *mem_ctx,
69 : const char *inbuf,
70 : size_t *outbufsize)
71 : {
72 : int ret;
73 43 : unsigned char *b64decoded = NULL;
74 : unsigned int size;
75 : unsigned char *outbuf;
76 :
77 : /* initialize NSS if needed */
78 43 : ret = nspr_nss_init();
79 43 : if (ret != EOK) {
80 0 : return NULL;
81 : }
82 :
83 43 : b64decoded = ATOB_AsciiToData(inbuf, &size);
84 43 : if (!b64decoded) return NULL;
85 :
86 43 : outbuf = talloc_memdup(mem_ctx, b64decoded, size);
87 43 : PORT_Free(b64decoded);
88 43 : if (!outbuf) return NULL;
89 :
90 43 : *outbufsize = size;
91 43 : return outbuf;
92 : }
|