使用 libssl 进行错误的 Base64 编码
假设以下代码,我的 Base64 编码中有奇怪的错误。
#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==
作为回报,这是很好的结果。
之前的源码有什么问题。
Assuming the following code, i have strange error in my base64 encodings.
#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;
}
I compile it with gcc test.c -o test -lcrypto
if I run :
./test testtes
I have dGVzdHRlcw==�
in result.. instead of dGVzdHRlcw==
if I run :
./test test
I have dGVzdA==
in return, which is the good result.
What's wrong with the previous source code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您缺少“+1”,因此缓冲区中没有空间用于空终止符。
You're missing the '+1', so there's no room in the buffer for the null-terminator.