base64.cpp 2.05 KB
Newer Older
1
/*
Sébastien Blin's avatar
Sébastien Blin committed
2
 *  Copyright (C) 2004-2019 Savoir-faire Linux Inc.
3
4
5
6
7
 *
 *  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.
Guillaume Roguez's avatar
Guillaume Roguez committed
8
 *
9
10
11
12
13
14
15
16
17
18
 *  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, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.
 */

19
#include "base64.h"
20
#include "sip/sip_utils.h"
21

22
23
#include <stdint.h>
#include <stdlib.h>
24
25
26
#include <iostream>
#include <pjlib.h>
#include <pjlib-util/base64.h>
27

Adrien Béraud's avatar
Adrien Béraud committed
28
namespace jami {
29
30
31
32
33
34
namespace base64 {

std::string
encode(const std::vector<uint8_t>::const_iterator begin,
       const std::vector<uint8_t>::const_iterator end)
{
35
    int input_length = std::distance(begin, end);
36
37
38
    if (input_length == 0)
        return {};

Guillaume Roguez's avatar
Guillaume Roguez committed
39
    int output_length = PJ_BASE256_TO_BASE64_LEN(input_length);
40
41
    std::string out;
    out.resize(output_length);
42
43
44
45
46

    if(pj_base64_encode( &(*begin), input_length, &(*out.begin()), &output_length) != PJ_SUCCESS) {
        throw base64_exception();
    }

47
48
49
50
51
52
53
54
55
56
57
58
59
    out.resize(output_length);
    return out;
}

std::string
encode(const std::vector<uint8_t>& dat)
{
    return encode(dat.cbegin(), dat.cend());
}

std::vector<uint8_t>
decode(const std::string& str)
{
60
61
62
    if (str.empty())
        return {};

Guillaume Roguez's avatar
Guillaume Roguez committed
63
    int output_length = PJ_BASE64_TO_BASE256_LEN(str.length());
64
    const pj_str_t input(sip_utils::CONST_PJ_STR(str));
65
66
67
68
69
70
71
72
73
74

    std::vector<uint8_t> out;
    out.resize(output_length);

    if(pj_base64_decode(&input, &(*out.begin()), &output_length) != PJ_SUCCESS) {
        throw base64_exception();
    }

    out.resize(output_length);
    return out;
75
76
}

Adrien Béraud's avatar
Adrien Béraud committed
77
}} // namespace jami::base64