2012-11-26 141 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

終止我不知道你爲什麼這樣做,要麼。 –