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