TDME2  1.9.200
Base64.cpp
Go to the documentation of this file.
1 #include <string>
2 #include <vector>
3 
4 #include <tdme/tdme.h>
6 
7 using std::string;
8 using std::vector;
9 
11 
12 void Base64::encode(const string& decodedString, string& encodedString) {
13  // see: https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c/34571089#34571089
14  string dictionary = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
15  int val = 0, valb = -6;
16  for (uint8_t c: decodedString) {
17  val = (val << 8) + c;
18  valb+= 8;
19  while (valb >= 0) {
20  encodedString.push_back(dictionary[(val >> valb) & 0x3F]);
21  valb-= 6;
22  }
23  }
24  if (valb > -6) encodedString.push_back(dictionary[((val << 8) >> (valb + 8)) & 0x3F]);
25  while (encodedString.size() % 4) encodedString.push_back('=');
26 }
27 
28 void Base64::encode(const vector<uint8_t>& decodedData, string& encodedString) {
29  // see: https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c/34571089#34571089
30  string dictionary = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
31  int val = 0, valb = -6;
32  for (uint8_t c: decodedData) {
33  val = (val << 8) + c;
34  valb+= 8;
35  while (valb >= 0) {
36  encodedString.push_back(dictionary[(val >> valb) & 0x3F]);
37  valb-= 6;
38  }
39  }
40  if (valb > -6) encodedString.push_back(dictionary[((val << 8) >> (valb + 8)) & 0x3F]);
41  while (encodedString.size() % 4) encodedString.push_back('=');
42 }
43 
44 void Base64::decode(const string& encodedString, string& decodedString) {
45  // see: https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c/34571089#34571089
46  string dictionary = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
47  std::vector<int> T(256, -1);
48  for (int i = 0; i < 64; i++) T[dictionary[i]] = i;
49  int val = 0, valb = -8;
50  for (uint8_t c: encodedString) {
51  if (T[c] == -1) break;
52  val = (val << 6) + T[c];
53  valb+= 6;
54  if (valb >= 0) {
55  decodedString.push_back(char((val >> valb) & 0xFF));
56  valb-= 8;
57  }
58  }
59 }
60 
61 void Base64::decode(const string& encodedString, vector<uint8_t>& decodedData) {
62  // see: https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c/34571089#34571089
63  string dictionary = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
64  std::vector<int> T(256, -1);
65  for (int i = 0; i < 64; i++) T[dictionary[i]] = i;
66  int val = 0, valb = -8;
67  for (uint8_t c: encodedString) {
68  if (T[c] == -1) break;
69  val = (val << 6) + T[c];
70  valb+= 6;
71  if (valb >= 0) {
72  decodedData.push_back(char((val >> valb) & 0xFF));
73  valb-= 8;
74  }
75  }
76 }
Base64 encoding/decoding class.
Definition: Base64.h:16
static const string decode(const string &encodedString)
Decodes an base64 encoded string.
Definition: Base64.h:34
static const string encode(const string &decodedString)
Encodes an string to base 64 string.
Definition: Base64.h:23