gpt4 book ai didi

c - 将证书写入 DER

转载 作者:太空宇宙 更新时间:2023-11-04 03:15:39 27 4
gpt4 key购买 nike

我正在尝试将 X509 证书写入内存中的 DER 格式。将其写入文件非常有效。

我需要 PEM 格式的证书,不带“-----BEGIN PRIVATE KEY-----”页眉、页脚或换行符。我无法弄清楚如何直接这样做......我正在输出到 der 和 base64 编码。

这行得通。

int X509_to_DER_file(X509 *cert) {
int res=0;

out = BIO_new(BIO_s_file());
if (NULL != out) {
if(BIO_write_filename(out, "my.der") > 0) {
res = i2d_X509_bio(out, cert);
}
BIO_free_all(out);
}
return (tres);
}

这不是。它返回并 mallocs 正确的字节数并且似乎正确地写出到内存但结果字符串不正确(前 15 个左右的位置是正确的)。

char *X509_to_DER_mem(X509 *cert) {
char *der = NULL;
bio = BIO_new(BIO_s_mem());

if (NULL != bio) {
//load cert into bio
if (0 == i2d_X509_bio(bio, cert)) {
BIO_flush(bio);
BIO_free(bio);
return NULL;
}

der = (char *) malloc(bio->num_write + 1);
if (NULL == der) {
BIO_free(bio);
return NULL;
}

memset(der, 0, bio->num_write + 1);
BIO_read(bio, der, bio->num_write);
// Appears to work put "der" is incomplete.
BIO_free(bio);
}

return der;
}

最佳答案

It returns and mallocs the correct number of bytes and appears to write out to memory correctly but the resulting string is incorrect

i2d_X509_bio() 的结果不是(以零结尾的)字符串,而是一堆字节。如果您尝试将它作为字符串写入文件,它可能看起来不完整,因为您可能会在到达末尾之前的某个位置遇到 0 字节。因此,除了 char * 结果之外,您的函数 X509_to_DER_mem() 还必须返回构成结果的字节数。

关于内存BIO,另一种获取其数据的方法是使用BIO_get_mem_data()。功能。像这样:

char *ptr = NULL;
long len = BIO_get_mem_data(bio, &ptr);
der = malloc(len);
memcpy(der, ptr, len);

最后,您的实际问题是

I need the Cert in PEM format without the "-----BEGIN PRIVATE KEY-----" header, footer or newlines.

用DER格式写证书好像不能给你你需要的。 This answer to another SO question解释了如何使用函数 PEM_read_bio()结合EVP_EncodeBlock()为此目的。

关于c - 将证书写入 DER,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52210793/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com