我使用libxml2创建一个xml文档,其中包含C语言中的base64编码文本。 但是,当我尝试添加包含base64编码的元素然后打印xml时,该元素为空。我还添加了printf来检查编码是否完成并打印出来。
这是我的计划:
xmlChar* createImportPKCS12Xml(char* userId, char* pkcs12, char* password, char* passwordForPkcs12) {
xmlNodePtr personElem;
xmlNodePtr userIdElem;
xmlNodePtr pkcs12Elem;
xmlNodePtr passwordElem;
xmlNodePtr pkcs12PasswordElem;
xmlDocPtr doc;
xmlNodePtr root_node;
xmlChar *xmlbuff;
int buffersize;
doc = xmlNewDoc(BAD_CAST "1.0");
root_node = xmlNewNode(NULL, BAD_CAST "root");
xmlDocSetRootElement(doc, root_node);
root_node = xmlDocGetRootElement(doc);
char* base = toBase64("abdsd");
printf(base);
personElem = xmlNewChild(root_node, NULL, BAD_CAST PERSON_ELEM, NULL);
userIdElem = xmlNewChild(personElem, NULL, BAD_CAST USER_ID_ELEM, BAD_CAST userId);
pkcs12Elem = xmlNewChild(root_node, NULL, BAD_CAST PKCS12_ELEM, BAD_CAST base);
passwordElem = xmlNewChild(root_node, NULL, BAD_CAST PASSWORD_ELEM, BAD_CAST password);
pkcs12PasswordElem = xmlNewChild(root_node, NULL, BAD_CAST PKCS12_PASSWORD_ELEM, BAD_CAST passwordForPkcs12);
if ((personElem == NULL)
|| (userIdElem == NULL)
|| (passwordElem == NULL)
|| (pkcs12PasswordElem == NULL)
|| (pkcs12Elem == NULL)) {
exit(EXIT_FAILURE);
}
xmlDocDumpFormatMemory(doc, &xmlbuff, &buffersize, 1);
xmlFreeDoc(doc);
xmlCleanupParser();
return xmlbuff;
}
对于base64编码,我使用的是openssl:
char* toBase64(char* str) {
BIO *bio, *b64;
b64 = BIO_new(BIO_f_base64());
bio = BIO_new_fp(stdout, BIO_NOCLOSE);
BIO_push(b64, bio);
BIO_write(b64, str, strlen(str));
BIO_flush(b64);
char* output = NULL;
int sz = BIO_get_mem_data(b64, &output);
BIO_free_all(b64);
return output;
}
使用普通文本没有问题。有人有同样的问题,可以帮忙吗?或者有人可以用libxml2建议一种不同的方法吗?
编辑1: 问题出在toBase64函数中。我改变之后一切正常:
char* toBase64(char* str) {
BIO *bio, *b64;
BUF_MEM *bufferPtr;
b64 = BIO_new(BIO_f_base64());
bio = BIO_new(BIO_s_mem());
bio = BIO_push(b64, bio);
BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL); //Ignore newlines - write everything in one line
BIO_write(bio, str, strlen(str));
BIO_flush(bio);
BIO_get_mem_ptr(bio, &bufferPtr);
BIO_set_close(bio, BIO_NOCLOSE);
BIO_free_all(bio);
char* output;
output=(*bufferPtr).data;
return output;
}
答案 0 :(得分:2)
编码函数的尾部看起来很吓人:
char* output = NULL;
int sz = BIO_get_mem_data(b64, &output);
BIO_free_all(b64);
return output;
您确定BIO_free_all()
之后输出指针有效吗?