基于openssl的base64编解码
base64原理
base64是一种编码,并不是一种加密方式。一串base64编码的数据被任何人得到都可以进行解码。
base64编码原理建议参考:base64编码原理
基于openssl的base64编码
size_t BcBase64Encode(const void* data, int data_len, string& res)
{
BIO* b64 = BIO_new(BIO_f_base64());
BIO* 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_len);
BIO_ctrl(bio, BIO_CTRL_FLUSH, 0, NULL);
BUF_MEM* bptr = NULL;
BIO_get_mem_ptr(bio, &bptr);
size_t slen = bptr->length;
auto buffer = new char[slen + 2];
memset(buffer, '\0', slen + 2);
memcpy(buffer, bptr->data, slen);
buffer[slen] = '\0';
res = buffer;
delete[] buffer;
//BIO_free_all(b64);
BIO_free_all(bio);
return slen;
}
基于openssl的base64解码
void Base64Decode(const char* input, int in_length, string& out)
{
BIO* b64 = NULL;
BIO* bio = NULL;
b64 = BIO_new(BIO_f_base64());
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
bio = BIO_new_mem_buf(input, in_length);
bio = BIO_push(b64, bio);
auto output = (char*)malloc(in_length);
memset(output, '\0', in_length);
auto len = BIO_read(bio, output, in_length);
out = output;
free(output);
BIO_free_all(bio);
//BIO_free_all(b64);
}