用openssl的evp进行base64编解码 C++

使用openssl的evp进行base64编解码有2种方式:

第一种:


#include "openssl/evp.h"
#include "string"

/******************************************************************************
    base64
******************************************************************************/
std::string base64_encodestring(const std::string &text ){
    EVP_ENCODE_CTX ectx;
    int size = text.size()*2;
    size = size > 64 ? size : 64;
    unsigned char* out = (unsigned char*)malloc( size );
    int outlen = 0;
    int tlen = 0;
    printf("text.size = %d\n", text.size());
    EVP_EncodeInit( &ectx );
    EVP_EncodeUpdate( &ectx, out, &outlen, (const unsigned char*)text.c_str(), text.size() );
    tlen += outlen;
    EVP_EncodeFinal( &ectx, out+tlen, &outlen );
    tlen += outlen;

    std::string str( (char*)out, tlen );
    free( out );
    return str;
}

std::string base64_decodestring(const std::string &text ){
    EVP_ENCODE_CTX ectx;
    unsigned char* out = (unsigned char*)malloc( text.size() );
    int outlen = 0;
    int tlen = 0;

    EVP_DecodeInit( &ectx );
    EVP_DecodeUpdate( &ectx, out, &outlen, (const unsigned char*)text.c_str(), text.size() );
    tlen += outlen;
    EVP_DecodeFinal( &ectx, out+tlen, &outlen );
    tlen += outlen;

    std::string data( (char*)out, tlen );
    free( out );
    return data;
}
这种方法对于编码结果超过64字节的,会自动用'\n'分隔,最终的结果:xxx\nxxx\nxx\n。(其中xxx为64字节,xx<=64字节),但对于要编解码的字符串长度非常大的情况,需循环调用EVP_EncodeUpdate及EVP_DecodeUpdate 进行编解码。


第二种:

#include "openssl/evp.h"
#include "string"

int32_t Base64Encode(const char *encoded, int encoded_length, char *decoded){
    return EVP_EncodeBlock((unsigned char*)decoded, (const unsigned char*)encoded, encoded_length);
}

int32_t Base64Decode(const char *encoded, int encoded_length, char *decoded) {
    return EVP_DecodeBlock((unsigned char*)decoded, (const unsigned char*)encoded, encoded_length);
}
直接调用一个API进行编解码(针对编解码字符串长度较小的),如编码结果超过64字节,不会自动添加'\n'换行。

以上说明中,字符串长度较大、较小暂无准确值。







转载于:https://my.oschina.net/zmlblog/blog/209017

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值