summaryrefslogtreecommitdiffstats
path: root/src/uscxml/util/Base64.hpp
blob: a106a124b43b90c5ce9b510de56e1e2d8bd2365c (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
// taken from http://www.adp-gmbh.ch/cpp/common/base64.html
#ifndef BASE64_H_5FKG12HF
#define BASE64_H_5FKG12HF

extern "C" {
#include "Base64.h"
}

#include <stdlib.h>
#include <string>
#include "uscxml/Common.h"

namespace uscxml {

USCXML_API inline std::string base64Encode(const char* data, unsigned int len) {
	base64_encodestate* ctx = (base64_encodestate*)malloc(sizeof(base64_encodestate));
	base64_init_encodestate(ctx);
	
	/**
	 * Wikipedia: Very roughly, the final size of Base64-encoded binary data is equal to 1.37
	 * times the original data size + 814 bytes (for headers). The size of the decoded data can
	 * be approximated with this formula:
	 */
	
	char* out = (char*)malloc(len * 1.4 + 814);
	base64_encode_block(data, len, out, ctx);
	free(ctx);
	std::string result(out);
	free(out);
	return result;
}

USCXML_API inline std::string base64Decode(const std::string& data) {
	base64_decodestate* ctx = (base64_decodestate*)malloc(sizeof(base64_decodestate));
	base64_init_decodestate(ctx);
	
	char* out = (char*)malloc(data.size());
	base64_decode_block(data.data(), data.size(), out, ctx);
	free(ctx);
	std::string result(out);
	free(out);
	return result;
}

}
#endif /* end of include guard: BASE64_H_5FKG12HF */