用openssl的evp進行base64編解碼 C++

使用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

相關文章
相關標籤/搜索