c - 将证书写入 DER

标签 c soap openssl der wsse

我正在尝试将 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/

相关文章:

java - 使用 JAVA 和 SOAP Web 服务的 SSRS 呈现报告

c++ - Boost、asio、https 和主机/证书验证

java - 来自Bouncy CaSTLe的ECIES对应的ECC解密

encryption - BCrypt 的主要 C/C++ 库是什么?

c - 有没有办法用 C 宏代替普通的 C 代码

c - 如何检查指定用户是否是本地计算机上的管理员?

c++ - C/C++ 中的无限循环

c - 随机和指针不起作用

soap - 寻找 Java 库/API 来为带有附件的 SOAP 消息实现 WS-Security(SwA)

java - 如何使用 jaxb2-maven-plugin 2.x 从 WSDL 生成 Java 类?