openssl----base64

378 阅读1分钟

encode

int Base64Encode(const std::string &in, std::string &out) {
    if (in.empty() || !out.empty()) {
        return -1;
    }

    BIO *b64 = BIO_new(BIO_f_base64());
    if (b64 == nullptr) {
        return -2;
    }
    BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);

    BIO *bmem = BIO_new(BIO_s_mem());
    if (bmem == nullptr) {
        return -3;
    }

    b64 = BIO_push(b64, bmem);

    BIO_write(b64, in.data(), in.size());
    BIO_flush(b64);

    BUF_MEM *bptr;
    BIO_get_mem_ptr(b64, &bptr);
    out.assign(bptr->data, bptr->length);

    BIO_free_all(b64);

    return 0;
}

decode

int Base64Decode(const std::string &in, std::string &out) {
    if (in.empty() || !out.empty()) {
        return -1;
    }

    BIO *b64 = BIO_new(BIO_f_base64());
    if (b64 == nullptr) {
        return -2;
    }
    BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);

    BIO *bmem = BIO_new_mem_buf(const_cast<char*>(in.data()), in.size());
    if(bmem == nullptr) {
        return -3;
    }

    b64 = BIO_push(b64, bmem);

    // 解码后的数据小于in.size
    std::shared_ptr<char> buf_manager(new char[in.size()]);

    char *buf = buf_manager.get();
    int len = in.size();
    len = BIO_read(b64, buf, len);
    if (len <= 0) {
        return -4;
    }

    out.assign(buf, len);

    BIO_free_all(b64);

    return 0;
}