openssl base64

openssl base64

介绍

linux上想用到base64,网上也没找到类似libbase64这种轻量的库,只能用openssl了
没什么好介绍的,原理懂的都懂,掉它的api,再加判断就完事了

Demo

#include "openssl/bio.h"
#include "openssl/evp.h"
#include "openssl/buffer.h"
#include <iostream>
#include <cstring>

int decode_base64(const char* buf, int size, char** bufOut);
int encode_base64(const char* buf, int size, char** bufOut);

int main()
{
    const char* p = "hello 123\n321 olleh";
    char* enbuf = NULL;
    char* debuf = NULL;

    int n = encode_base64(p, strlen(p), &enbuf);
    if(n == -1)
    {
        std::cout << "encode_base64 failed" << std::endl;
        return -1;
    }
    std::cout << n << std::endl;
    std::cout << enbuf << std::endl;

    n = decode_base64(enbuf, strlen(enbuf), &debuf);
    if(n == -1)
    {
        std::cout << "decode_base64 failed" << std::endl;
        return -1;
    }
    std::cout << n << std::endl;
    std::cout << debuf << std::endl;
    return 0;
}

int decode_base64(const char* buf, int size, char** bufOut)
{
    BIO* bioMem = NULL;
    BIO* bioB64 = NULL;

    char* pData = (char*)malloc(size);
    if(pData == NULL)
    {
        return -1;
    }
    memset(pData, 0, size);

    bioB64 = BIO_new(BIO_f_base64());
    if(bioB64 == NULL)
    {
        return -1;
    }

    BIO_set_flags(bioB64, BIO_FLAGS_BASE64_NO_NL);

    bioMem = BIO_new_mem_buf(buf, size);
    if(bioMem == NULL)
    {
        return -1;
    }

    bioMem = BIO_push(bioB64, bioMem);
    int n = BIO_read(bioMem, pData, size);
    BIO_free_all(bioMem);
    if(n <= 0)
    {
        return -1;
    }

    *bufOut = pData;

    return n;
}

int encode_base64(const char* buf, int size, char** bufOut)
{
    BIO* bioMem = NULL;
    BIO* bioB64 = NULL;
    BUF_MEM* buf_mem;

    bioB64 = BIO_new(BIO_f_base64());
    if(bioB64 == NULL)
    {
        return -1;
    }

    BIO_set_flags(bioB64, BIO_FLAGS_BASE64_NO_NL);

    bioMem = BIO_new(BIO_s_mem());
    if(bioMem == NULL)
    {
        return -1;
    }

    bioB64 = BIO_push(bioB64, bioMem);
    if(BIO_write(bioB64, buf, size) <= 0)
    {
        return -1;
    }
    
    BIO_flush(bioB64);

    BIO_get_mem_ptr(bioB64, &buf_mem);
    BIO_set_close(bioB64, BIO_NOCLOSE);

    char* pData = (char*)malloc(buf_mem->length + 1);
    if(pData == NULL)
    {
        return -1;
    }
    memcpy(pData, buf_mem->data, buf_mem->length);
    pData[buf_mem->length] = '\0';

    BIO_free_all(bioB64);

    *bufOut = pData;
    return buf_mem->length;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值