在 C 中使用 OpenSSL 获取 .der 格式的公钥证书 [英] Get publickey certificate in .der format with OpenSSL in C

查看:278
本文介绍了在 C 中使用 OpenSSL 获取 .der 格式的公钥证书的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 C 语言中的 OpenSSL 从证书中提取公钥,然后将其转换为 .der 格式,但我无法做到.

目标是提取到公钥以实现固定,如下所示:https://curl.haxx.se/libcurl/c/CURLOPT_PINNEDPUBLICKEY.html(公钥提取)

我使用的是本教程中的代码.

BIO *certbio = NULL;X509 *证书 = NULL;ret = BIO_read_filename(certbio, cert_path);cert = PEM_read_bio_X509(certbio, NULL, 0, NULL));EVP_PKEY *pkey = X509_get_pubkey(cert));

如何将 EVP_PKEY* 转换为 .der 格式的无符号字符*?或者以 .pem 格式获取它然后转换它?谢谢

解决方案

你可以使用函数 i2d_PUBKEY() 来达到这个目的:

https://www.openssl.org/docs/man1.1.0/crypto/i2d_PUBKEY.html

 int i2d_PUBKEY(EVP_PKEY *a, unsigned char **pp);

注意手册页上的这一重要声明:

<块引用>

d2i_PUBKEY() 和 i2d_PUBKEY() 对 EVP_PKEY 进行解码和编码使用 SubjectPublicKeyInfo 格式的结构.他们否则遵循其他 ASN.1 函数的约定,例如 d2i_X509().

d2i_X509() 手册页上的重要说明:

int i2d_TYPE(TYPE *a, unsigned char **ppout);

<块引用>

i2d_TYPE() 将 a 指向的结构编码为 DER 格式.如果 ppout 不为 NULL,则将 DER 编码数据写入*ppout 处的缓冲区,并将其递增到刚好指向数据之后书面.如果返回值为负则发生错误,否则它返回编码数据的长度.

因此使用 NULL 第二个参数调用一次以发现所需的缓冲区长度.使用指向缓冲区的指针再次调用它以填充数据 - 但请注意,您的指针将在之后递增(常见的混淆来源).

I am trying to extract the publickey from a certificate using OpenSSL in C and then convert it to .der format, but I cannot manage to do it.

The goal is to extract to extract to public key to implement pinning, like here: https://curl.haxx.se/libcurl/c/CURLOPT_PINNEDPUBLICKEY.html (public key extraction)

I am using the code from this tutorial.

BIO *certbio = NULL;
X509 *cert = NULL;
ret = BIO_read_filename(certbio, cert_path);
cert = PEM_read_bio_X509(certbio, NULL, 0, NULL));
EVP_PKEY *pkey = X509_get_pubkey(cert));

How can I convert from EVP_PKEY* to an unsigned char* in .der format? Or perhaps get it in .pem format and then convert it? Thanks

解决方案

You can use the function i2d_PUBKEY() for this purpose:

https://www.openssl.org/docs/man1.1.0/crypto/i2d_PUBKEY.html

 int i2d_PUBKEY(EVP_PKEY *a, unsigned char **pp);

Note this important statement on the man page:

d2i_PUBKEY() and i2d_PUBKEY() decode and encode an EVP_PKEY structure using SubjectPublicKeyInfo format. They otherwise follow the conventions of other ASN.1 functions such as d2i_X509().

And this important note on the d2i_X509() man page:

int i2d_TYPE(TYPE *a, unsigned char **ppout);

i2d_TYPE() encodes the structure pointed to by a into DER format. If ppout is not NULL, it writes the DER encoded data to the buffer at *ppout, and increments it to point after the data just written. If the return value is negative an error occurred, otherwise it returns the length of the encoded data.

So call it once with a NULL second parameter to discover the required length of the buffer. Call it again with a pointer to your buffer to fill in the data - but note that your pointer will be incremented afterwards (a common source of confusion).

这篇关于在 C 中使用 OpenSSL 获取 .der 格式的公钥证书的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆