【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.

你可能感兴趣的:(base64,decode,encode,OpenSSL,BIO-filter)