【OpenSSL】base64 with BIO filter

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.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值