您的位置:首页 > 运维架构

使用openssl进行base64编码 解码

2013-12-09 15:55 691 查看
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 );
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: