使用openssl的evp进行base64编解码有2种方式: 编码
第一种: spa
#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 进行编解码。
第二种: code
#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'换行。
以上说明中,字符串长度较大、较小暂无准确值。 ssl