Skip to content

Commit

Permalink
Add base64 string encoder/decoder (#79)
Browse files Browse the repository at this point in the history
* Add base64 string encoder/decoder

Signed-off-by: Juan Lopez Fernandez <[email protected]>

* Uncrustify

Signed-off-by: Juan Lopez Fernandez <[email protected]>

---------

Signed-off-by: Juan Lopez Fernandez <[email protected]>
  • Loading branch information
juanlofer-eprosima authored Aug 30, 2023
1 parent e3d805d commit 900874d
Show file tree
Hide file tree
Showing 2 changed files with 92 additions and 0 deletions.
34 changes: 34 additions & 0 deletions cpp_utils/include/cpp_utils/utils.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -289,11 +289,45 @@ CPP_UTILS_DllAPI
std::set<Key> get_keys(
const std::map<Key, Value>& map);

/**
* @brief Get std::unordered_map keys.
*
* Obtain the set of keys relative to a std::unordered_map.
*
* @param map [in] map whose keys are returned
*
* @return map keys
*/
template <typename Key, typename Value>
CPP_UTILS_DllAPI
std::set<Key> get_keys(
const std::unordered_map<Key, Value>& map);

/**
* @brief Encode string using base64.
*
* @param in [in] string to encode
*
* @return string in base64
*/
CPP_UTILS_DllAPI
std::string base64_encode(
const std::string& in);

/**
* @brief Decode base64 string.
*
* @param in [in] string in base64 to decode
*
* @return decoded string
*/
CPP_UTILS_DllAPI
std::string base64_decode(
const std::string& in);

//! Set of characters used in base64 encoding/decoding algorithms
const std::string base64_alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

} /* namespace utils */
} /* namespace eprosima */

Expand Down
58 changes: 58 additions & 0 deletions cpp_utils/src/cpp/utils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -232,5 +232,63 @@ std::vector<std::string> split_string(
return result;
}

// FROM: https://gist.github.com/williamdes/308b95ac9ef1ee89ae0143529c361d37
std::string base64_encode(
const std::string& in)
{
std::string out;

int val = 0, valb = -6;
for (unsigned char c : in)
{
val = (val << 8) + c;
valb += 8;
while (valb >= 0)
{
out.push_back(base64_alphabet[(val >> valb) & 0x3F]);
valb -= 6;
}
}
if (valb > -6)
{
out.push_back(base64_alphabet[((val << 8) >> (valb + 8)) & 0x3F]);
}
while (out.size() % 4)
{
out.push_back('=');
}
return out;
}

// FROM: https://gist.github.com/williamdes/308b95ac9ef1ee89ae0143529c361d37
std::string base64_decode(
const std::string& in)
{
std::string out;

std::vector<int> T(256, -1);
for (int i = 0; i < 64; i++)
{
T[base64_alphabet[i]] = i;
}

int val = 0, valb = -8;
for (unsigned char c : in)
{
if (T[c] == -1)
{
break;
}
val = (val << 6) + T[c];
valb += 6;
if (valb >= 0)
{
out.push_back(char((val >> valb) & 0xFF));
valb -= 8;
}
}
return out;
}

} /* namespace utils */
} /* namespace eprosima */

0 comments on commit 900874d

Please sign in to comment.