Skip to content

Instantly share code, notes, and snippets.

@razzbee
Last active September 3, 2020 19:13
Show Gist options
  • Save razzbee/fa6c7da69b00502f0ae195ce55788813 to your computer and use it in GitHub Desktop.
Save razzbee/fa6c7da69b00502f0ae195ce55788813 to your computer and use it in GitHub Desktop.
Encoding and Decoding Base64 string using Libcodium C library in C++
``
//
// 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
``
@rikonaka
Copy link

Thanks for your code.😁

@KVPV
Copy link

KVPV commented Sep 3, 2020

where is here decode base64?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment