2
假設下面的代碼,我在我的base64編碼中有奇怪的錯誤。Bad Base64使用libssl編碼
#include <openssl/bio.h>
#include <openssl/buffer.h>
#include <stdio.h>
#include <string.h>
char * base64(unsigned char * input, int length) {
BIO *b64 = NULL;
BIO * bmem = NULL;
BUF_MEM *bptr = NULL;
char * output = NULL;
b64 = BIO_new((BIO_METHOD *)BIO_f_base64());
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
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);
output = (char *) calloc (bptr->length, sizeof(char));
memcpy(output, bptr->data, bptr->length);
BIO_free_all(b64);
return output;
}
int main(int argc, char *argv[]) {
char * based_string = NULL;
based_string = base64(argv[1], strlen(argv[1]));
printf("%s\n", based_string);
free(based_string);
return 0;
}
我gcc test.c -o test -lcrypto
編譯它,如果我跑:
./test testtes
我對結果dGVzdHRlcw==�
..而不是dGVzdHRlcw==
如果我運行:
./test test
我dGVzdA==
的回報,這是很好的結果。
以前的源代碼有什麼問題。
'sizeof(char)'被定義爲'1'。同樣在C中,你不應該從'malloc'或'calloc'強制返回值,因爲這可能會給你一個關於缺少原型的警告:在這裏你沒有包含''stdlib.h'',所以你的編譯器可能會首先將返回值爲'int',然後將其轉換爲'char *'並且稍微鬆散一點。在C++中,你必須進行轉換,但是在那裏你不會首先使用'calloc'。 – 2010-09-14 18:43:50