您的位置:首页 > 运维架构

【OpenSSL】base64 with BIO filter

2016-04-28 09:18 375 查看

Introduction

There are many ways to do base64 encoding/decoding in OpenSSL, Here are some demos code with BIO filter. Other ways, e.g. EVP_* will be introduced later Base64 with EVP.

Encode

std::string CX509Cert::b64enc(const std::string & str)
{
BIO* out = BIO_new(BIO_s_mem());// sink to memory.
if (!out){
return "";
}

BIO * b64 = BIO_new(BIO_f_base64());
if (!b64){
BIO_free(out);
return "";
}

out = BIO_push(b64, out);

BIO_write(out, (char *)str.c_str(), str.length());

BIO_flush(out);

BUF_MEM * bufptr = NULL;
BIO_get_mem_ptr(out, &bufptr);
std::string b64str = "";
b64str.append((char *)bufptr->data, bufptr->length);

BIO_free(b64);

return b64str;
}


Decode

std::string CX509Cert::b64dec(const std::string & b64str)
{
BIO * in = BIO_new_mem_buf((void*)b64str.c_str(), b64str.length());
if (!in) return "";

BIO * b64 = BIO_new(BIO_f_base64());
if (!b64){
BIO_free(in);
return "";
}

in = BIO_push(b64, in);

char buf [16] = "";
int bufsz = sizeof(buf);

std::string str = "";
for(;;){
int cb = BIO_read(in, buf, bufsz);
if (cb <= 0){
break;
}
str.append(buf, cb);
}

BIO_free(b64);

return str;
}


Note

BIO_free(b64) will also free in/out BIOs, so, remeber do NOT double free them.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: