Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Antonio Villanueva Segura
- * Fonctions d'encodage et de décodage Base64 <-> Hex base sur boost
- * g++ -o decode_base64 decode_base64.cpp -lboost_system
- */
- //g++ -o base64 base64.cpp -lboost_system
- #include <iostream>
- #include <string>
- #include <vector>
- //Hex Base64
- #include <boost/algorithm/hex.hpp>
- #include <boost/beast/core/detail/base64.hpp>
- using namespace std;//std::
- // conversion chaîne hexadécimale en base64 p.e '060200000000' ->BgIAAAAA
- // Fonction pour convertir une chaîne hexadécimale en bytes
- std::vector<unsigned char> hex_to_bytes(const std::string& hex) {
- std::vector<unsigned char> bytes;
- boost::algorithm::unhex(hex.begin(), hex.end(), std::back_inserter(bytes));
- return bytes;
- }
- // Fonction pour encoder des octets en Base64, retourne string
- std::string base64_encode(const std::vector<unsigned char>& bytes) {
- std::string base64;
- base64.resize(boost::beast::detail::base64::encoded_size(bytes.size()));
- base64.resize(boost::beast::detail::base64::encode(
- &base64[0], bytes.data(), bytes.size()));
- return base64;
- }
- //Décode Base64 en un système hexadécimal mais type de chaîne imprimable
- std::string base64_decode(const std::string &src) {
- using namespace boost::beast::detail::base64;
- //Base64 Decode dan un string mais de type Hex
- std::string destHex;
- destHex.resize(decoded_size(src.size()));
- std::pair<std::size_t, bool> result = decode(&destHex[0], src.data(), src.size());//adst[0],src,src.size
- destHex.resize(result.first); // Resize to the actual decoded size
- //Conversion Hex -> Hex String
- string HexString;
- std::ostringstream oss;
- for (auto item:destHex){
- oss << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(item);
- }
- std::string hex_representation = oss.str();
- return hex_representation;
- }
- int main (){
- string data="060200000000";
- vector <unsigned char > data_char=hex_to_bytes (data);
- cout <<"Data Hex : "<<data<<endl;
- string data_base64=base64_encode(data_char);//Encode
- cout <<"Base64 :"<< data_base64<<endl;
- string data_decoded=base64_decode(data_base64) ;
- if (data_decoded.empty()) {
- std::cerr << "Error: Decoded data is empty" << std::endl;
- return 1;
- }else {
- cout <<"Data Hex (decode) :"<< data_decoded<<endl;
- }
- return 0;
- }
Add Comment
Please, Sign In to add comment