Project Alice
Loading...
Searching...
No Matches
base64encode.hpp
Go to the documentation of this file.
1/*
2* Base64 encoding/decoding (RFC1341)
3* Copyright (c) 2005-2011, Jouni Malinen <j@w1.fi>
4*
5* This software may be distributed under the terms of the BSD license.
6* See README for more details.
7*/
8
9// 2016-12-12 - Gaspard Petit : Slightly modified to return a std::string
10// instead of a buffer allocated with malloc.
11
12#include <string>
13
14static const unsigned char base64_table[65] =
15"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
16
25std::string base64_encode(const char* src, size_t len) {
26 char* out, * pos;
27 const char* end, * in;
28
29 size_t olen;
30
31 olen = 4 * ((len + 2) / 3); /* 3-byte blocks to 4-byte */
32
33 if(olen < len)
34 return std::string(); /* integer overflow */
35
36 std::string outStr;
37 outStr.resize(olen);
38 out = (char*)&outStr[0];
39
40 end = src + len;
41 in = src;
42 pos = out;
43 while(end - in >= 3) {
44 *pos++ = base64_table[in[0] >> 2];
45 *pos++ = base64_table[((in[0] & 0x03) << 4) | (in[1] >> 4)];
46 *pos++ = base64_table[((in[1] & 0x0f) << 2) | (in[2] >> 6)];
47 *pos++ = base64_table[in[2] & 0x3f];
48 in += 3;
49 }
50
51 if(end - in) {
52 *pos++ = base64_table[in[0] >> 2];
53 if(end - in == 1) {
54 *pos++ = base64_table[(in[0] & 0x03) << 4];
55 *pos++ = '=';
56 } else {
57 *pos++ = base64_table[((in[0] & 0x03) << 4) |
58 (in[1] >> 4)];
59 *pos++ = base64_table[(in[1] & 0x0f) << 2];
60 }
61 *pos++ = '=';
62 }
63
64 return outStr;
65}
std::string base64_encode(const char *src, size_t len)