使用openssl进行base64编码 解码

http://hi.baidu.com/facile_fengsh/item/0dad1aafe7a5caaa29ce9dfc

static int base64_encode(unsigned char *str,int str_len,char *encode,int *encode_len)
{
    BIO *bmem, *b64;
    BUF_MEM *bptr;

    if ( !str || !encode )
    {
        return 1;
    }
    
    b64 = BIO_new( BIO_f_base64() );
    bmem = BIO_new( BIO_s_mem() );
    b64 = BIO_push( b64, bmem );
    BIO_write( b64, str, str_len ); //encode
    if ( BIO_flush( b64 ) );
    BIO_get_mem_ptr( b64, &bptr );
    if( bptr->length > *encode_len )
    {
        printf("encode_len too small\n");
        return 1; 
    }   
    *encode_len = bptr->length;
    memcpy( encode, bptr->data, bptr->length );
//  write(1,encode,bptr->length);
    BIO_free_all( b64 );
    return 0;
}

static int base64_decode(const char* input, int inLen, unsigned char* output, int *outLen)
{
    if (!input || !output)
    {
        return -1;
    }

    char *psz_tmp = malloc( inLen + 1 );
    if ( !psz_tmp )
    {
        abort();
    }
    memset( psz_tmp, 0, inLen + 1 );
    
    psz_tmp[inLen] = '\n';      // Openssl demand to have '\n' to end the string.
    memcpy(&psz_tmp[0], input, inLen);
    memset(output, 0 , *outLen);
    BIO * b642 = BIO_new(BIO_f_base64());
    BIO * bmem2 = BIO_new_mem_buf(&psz_tmp[0], inLen+1);
    // should not use the input directly, the follow is wrong
    //BIO * bmem2 = BIO_new_mem_buf( ( char * )input, inLen+1);
    bmem2 = BIO_push(b642, bmem2);
    *outLen = BIO_read(bmem2, output, *outLen);
    BIO_free_all(bmem2);
    return 0;
}

int main(int argc, char **argv)  
{  
    unsigned char *psz_init = ( unsigned char * )"1234567890";
    char psz_encode[4096] = {0};
    unsigned char psz_decode[4096] = {0};
    int i_outlen = 4096;
    if ( 0 != base64_encode( psz_init, strlen( ( char * )psz_init ), psz_encode, &i_outlen ) )
    {
        printf( "encode error!" );
    }
    printf( "\npsz_encode: %s", psz_encode );

    if ( 0 != base64_decode( psz_encode, strlen( psz_encode ), psz_decode, &i_outlen ) )
    {
        printf( "decode error!" );
    }
    printf( "\npsz_decode1: %s\n", psz_decode );
}



  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值