C++ Base64 Encoding Implementation
One way to implement Base64 encoding in C++ is by using an existing Base64 library, or by writing your own implementation. Here is an example of using an existing Base64 library:
#include <iostream>
#include <string>
#include <vector>
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/buffer.h>
std::string base64_encode(const std::vector<unsigned char> &data) {
BIO *bio, *b64;
BUF_MEM *bufferPtr;
b64 = BIO_new(BIO_f_base64());
bio = BIO_new(BIO_s_mem());
bio = BIO_push(b64, bio);
BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL);
BIO_write(bio, data.data(), data.size());
BIO_flush(bio);
BIO_get_mem_ptr(bio, &bufferPtr);
BIO_set_close(bio, BIO_NOCLOSE);
BIO_free_all(bio);
return std::string(bufferPtr->data, bufferPtr->length);
}
int main() {
std::string input = "Hello, World!";
std::vector<unsigned char> data(input.begin(), input.end());
std::string encoded = base64_encode(data);
std::cout << "Base64 encoded string: " << encoded << std::endl;
return 0;
}
This example demonstrates how to implement Base64 encoding using functions from the OpenSSL library. A base64_encode function is first defined to encode the input data in Base64, and then in the main function, the sample string “Hello, World!” is encoded and the result is output. The input data and output method can be modified according to actual needs.