Last active
October 9, 2024 03:34
-
-
Save razzbee/fa6c7da69b00502f0ae195ce55788813 to your computer and use it in GitHub Desktop.
Encoding and Decoding Base64 string using Libcodium C library in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
`` | |
// | |
// Created by Razak Zakari on 12/04/2018. | |
// | |
#define BASE64_VARIATION sodium_base64_VARIANT_ORIGINAL | |
#include <algorithm> | |
#include <math.h> | |
#include <vector> | |
#include "crypt.h" | |
extern "C" { | |
#include <sodium.h> | |
} | |
/** | |
* hidden fun, base64encode | |
*/ | |
std::string base64_encode(std::string bin_str){ | |
//bytes len | |
const size_t bin_len = bin_str.size(); | |
//base64_max_len | |
const size_t base64_max_len = sodium_base64_encoded_len(bin_len,BASE64_VARIATION); | |
//std::cout << base64_max_len << std::endl; | |
//base64 encoded var | |
std::string base64_str(base64_max_len-1,0); | |
char * encoded_str_char = sodium_bin2base64( | |
base64_str.data(), | |
base64_max_len, | |
(unsigned char *) bin_str.data(), | |
bin_len, | |
BASE64_VARIATION | |
); | |
if(encoded_str_char == NULL){ | |
throw "Base64 Error: Failed to encode string"; | |
} | |
//std::cout << sizeof(encoded_str_char) << "---" << base64_str.size() << std::endl; | |
return base64_str; | |
}//end | |
`` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for your code.😁