summaryrefslogtreecommitdiff
path: root/src/util/crypto/nss/nss_base64.c
blob: be3de487f9d9729d035dbd882ab5dcc628d25375 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/*
    Authors:
        Jakub Hrozek <jhrozek@redhat.com>

    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 <http://www.gnu.org/licenses/>.
*/

#include <talloc.h>

#include "util/util.h"
#include "util/crypto/nss/nss_util.h"

#include <base64.h>

/* 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;
}