介绍
linux上想用到base64,网上也没找到类似libbase64这种轻量的库,只能用openssl了
没什么好介绍的,原理懂的都懂,掉它的api,再加判断就完事了
Demo
#include "openssl/bio.h"
#include "openssl/evp.h"
#include "openssl/buffer.h"
#include <iostream>
#include <cstring>
int decode_base64(const char* buf, int size, char** bufOut);
int encode_base64(const char* buf, int size, char** bufOut);
int main()
{
const char* p = "hello 123\n321 olleh";
char* enbuf = NULL;
char* debuf = NULL;
int n = encode_base64(p, strlen(p), &enbuf);
if(n == -1)
{
std::cout << "encode_base64 failed" << std::endl;
return -1;
}
std::cout << n << std::endl;
std::cout << enbuf << std::endl;
n = decode_base64(enbuf, strlen(enbuf), &debuf);
if(n == -1)
{
std::cout << "decode_base64 failed" << std::endl;
return -1;
}
std::cout << n << std::endl;
std::cout << debuf << std::endl;
return 0;
}
int decode_base64(const char* buf, int size, char** bufOut)
{
BIO* bioMem = NULL;
BIO* bioB64 = NULL;
char* pData = (char*)malloc(size);
if(pData == NULL)
{
return -1;
}
memset(pData, 0, size);
bioB64 = BIO_new(BIO_f_base64());
if(bioB64 == NULL)
{
return -1;
}
BIO_set_flags(bioB64, BIO_FLAGS_BASE64_NO_NL);
bioMem = BIO_new_mem_buf(buf, size);
if(bioMem == NULL)
{
return -1;
}
bioMem = BIO_push(bioB64, bioMem);
int n = BIO_read(bioMem, pData, size);
BIO_free_all(bioMem);
if(n <= 0)
{
return -1;
}
*bufOut = pData;
return n;
}
int encode_base64(const char* buf, int size, char** bufOut)
{
BIO* bioMem = NULL;
BIO* bioB64 = NULL;
BUF_MEM* buf_mem;
bioB64 = BIO_new(BIO_f_base64());
if(bioB64 == NULL)
{
return -1;
}
BIO_set_flags(bioB64, BIO_FLAGS_BASE64_NO_NL);
bioMem = BIO_new(BIO_s_mem());
if(bioMem == NULL)
{
return -1;
}
bioB64 = BIO_push(bioB64, bioMem);
if(BIO_write(bioB64, buf, size) <= 0)
{
return -1;
}
BIO_flush(bioB64);
BIO_get_mem_ptr(bioB64, &buf_mem);
BIO_set_close(bioB64, BIO_NOCLOSE);
char* pData = (char*)malloc(buf_mem->length + 1);
if(pData == NULL)
{
return -1;
}
memcpy(pData, buf_mem->data, buf_mem->length);
pData[buf_mem->length] = '\0';
BIO_free_all(bioB64);
*bufOut = pData;
return buf_mem->length;
}