2012-11-26 144 views
-2

我使用用于编码和解码为base64的目的OpenSSL库,这是我的加密代码加密和解密使用Base64算法

#include <openssl/buffer.h> 
#include <stdlib.h> 
char *base64(const unsigned char *input, int length); 

int main(int argc, char **argv) 
{ 
    char nonce[10]; 
    srand(time(NULL)); 
    printf("rand():%d\n", rand()); 
    sprintf(nonce, "%d", rand()); 
    char *output = base64(nonce, sizeof(nonce)); 
    printf("Base64: *%s*\n", output); 
    free(output); 
} 

char *base64(const unsigned char *input, int length) 
{ 
    BIO *bmem, *b64; 
    BUF_MEM *bptr; 
    char *buff; 
    b64 = BIO_new(BIO_f_base64()); 
    bmem = BIO_new(BIO_s_mem()); 
    b64 = BIO_push(b64, bmem); 
    BIO_write(b64, input, length); 
    BIO_flush(b64); 
    BIO_get_mem_ptr(b64, &bptr); 
    buff = (char *) malloc(bptr->length); 
    memcpy(buff, bptr->data, bptr->length-1); 
    buff[bptr->length-1] = '\0'; 
    BIO_free_all(b64); 
    return buff; 
} 

中的O /的该p时被NjI0MjQ3MwAECA ==兰特()产量为1308702736(这是为兰特根O/p的一个实例的一个例子),当我使用的解码功能,以这个值i得到6242473,这完全是DIFF解码,我有解码时获得1308702736,

我的解码功能如下

#include <string.h> 
#include <openssl/sha.h> 
#include <openssl/hmac.h> 
#include <openssl/evp.h> 
#include <openssl/bio.h> 
#include <openssl/buffer.h> 

char *unbase64(unsigned char *input, int length); 

int main(int argc, char **argv) 
{ 
    char *output = unbase64("NjI0MjQ3MwAECA==\n", strlen("NjI0MjQ3MwAECA==\n")); 
    printf("Unbase64: *%s*\n", output); 
    free(output); 
} 
char *unbase64(unsigned char *input, int length) 
{ 
    BIO *b64, *bmem; 
    char *buffer = (char *)malloc(length); 
    memset(buffer, 0, length); 
    b64 = BIO_new(BIO_f_base64()); 
    bmem = BIO_new_mem_buf(input, length); 
    bmem = BIO_push(b64, bmem); 
    BIO_read(bmem, buffer, length); 
    BIO_free_all(bmem); 

    return buffer; 
} 

注意:要编译此代码v必须使用-lcrypto 我需要一个解决此问题的帮助我卡在这里,搜索解决方案但没有得到任何,并且有一个疑问为什么输入到base64解码器b终止\ n?可以一个一个帮我在这

+0

阅读您尝试使用的函数的[documentation](http://pubs.opengroup.org/onlinepubs/009695399/functions/rand.html)。 – 2012-11-26 10:24:11

回答

3
printf("rand():%d\n", rand()); 
sprintf(nonce, "%d", rand()); 

你叫rand两次,给你两个不同的号码。 NjI0MjQ3MwAECA==解码为624247

+2

哎哟。这一个伤害。 – 2012-11-26 10:23:22

+0

@大卫·施瓦茨:感谢您指出我的愚蠢,并有一个疑问,为什么的base64解码器b。通过\ n – Manu

+1

终止我不知道你为什么这样做,要么。 –