使用openssl 实现base64编解码

  1. 借助BIO对象是OpenSSL中的一种抽象,用于处理各种类型的输入/输出,如文件、套接字、内存等。

  2. BIO链,通过BIO_push()接口,可以实现b64对象和需要编解码的字符串的链接。
    – BIO_read(),使字符串经过B64解码,读出;
    – BIO_write(),使字符串经过B64编码,写入BIO_mem, 再从memory读出。
    注:BIO_write()后一定需要调用BIO_flush(),将BIO_mem 内部缓冲区的数据都写出去。
    在这里插入图片描述
    下面是自己调试的代码:

#include <openssl/evp.h>
#include <openssl/buffer.h>
#include <string.h>
#include <string> 
#include <iostream>

using namespace std;

std::string base64_decode(const std::string& input) {
    BIO* b64 = BIO_new(BIO_f_base64());
    BIO* bio = BIO_new_mem_buf(input.data(), input.size());
    bio = BIO_push(b64, bio);
    std::string output;
    char inbuf[512];
    int inlen;
    while ((inlen = BIO_read(bio, inbuf, 512)) > 0)
        output.append(inbuf, inlen);

    BIO_free_all(bio);
    return output;
}

std::string base64_encode(const std::string& input) {
    std::string output;
    BIO* b64 = BIO_new(BIO_f_base64());
    BIO* bio = BIO_new(BIO_s_mem());
    bio = BIO_push(b64, bio);

    BIO_write(bio, input.c_str(), input.size());

    BIO_flush(bio);//important step for bio_write

    BUF_MEM* bptr = nullptr;
	//获取bio内存指针
	BIO_get_mem_ptr(bio, &bptr);
    char * outbuf = (char *)malloc(bptr->length);
    memcpy(outbuf, bptr->data, bptr->length);
    //printf("%s\n",outbuf);
    output=outbuf;
    free(outbuf);
    BIO_free_all(bio);
    return output;
}

int main()
{
    string str="abcdef";
    cout<<str<<endl;
    string enstr=base64_encode(str);
    cout<<enstr<<endl;
    string destr=base64_decode(enstr);
    cout<<destr<<endl;
    return 0;
}

参考:https://blog.csdn.net/qq_44630120/article/details/108590448

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值