#include <iostream>
#include <cstring>
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/buffer.h>

std::string base64_encode(const unsigned char* input, int length) {
    BIO* bio = BIO_new(BIO_f_base64());
    BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL);

    BIO* bmem = BIO_new(BIO_s_mem());
    bio = BIO_push(bio, bmem);

    BIO_write(bio, input, length);
    BIO_flush(bio);

    BUF_MEM* bptr;
    BIO_get_mem_ptr(bio, &bptr);

    std::string result(bptr->data, bptr->length);

    BIO_free_all(bio);

    return result;
}

std::string base64_decode(const char* input) {
    BIO* bio = BIO_new(BIO_f_base64());
    BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL);

    BIO* bmem = BIO_new_mem_buf(input, -1);
    bio = BIO_push(bio, bmem);

    char buffer[1024];
    int length = BIO_read(bio, buffer, sizeof(buffer));

    BIO_free_all(bio);

    return std::string(buffer, length);
}

int main() {
    const char* originalText = "Hello, Base64!";
    int originalLength = std::strlen(originalText);

    // Base64 编码
    std::string encodedText = base64_encode(reinterpret_cast<const unsigned char*>(originalText), originalLength);
    std::cout << "Base64 Encoded: " << encodedText << std::endl;

    // Base64 解码
    std::string decodedText = base64_decode(encodedText.c_str());
    std::cout << "Base64 Decoded: " << decodedText << std::endl;

    return 0;
}
