简体   繁体   中英

[OpenSSL} Read certificate.pem to get the public key in RSA format in C lang

I'm a noob on the OpenSSL and key formats. I'm using C lang.

I want to change my certificate file that is in a pem format (ABCcert.pem file - It starts with the -----BEGIN CERTIFICATE----- and ends with -----END CERTIFICATE-----) to a RSA public key using C.

In other words, I have a certificate which's a pem format, and I want to take the public Key out of it and encrypt my message.

I found a lot of great answers using the openssl console, but I only want to use C lang.

Could anyone help?

You want PEM_read_X509() :

 X509 *PEM_read_X509(FILE *fp, X509 **x, pem_password_cb *cb, void *u); . . .

The PEM read functions all take an argument TYPE **x and return a TYPE * pointer. Where TYPE is whatever structure the function uses. If x is NULL then the parameter is ignored. If x is not NULL but *x is NULL then the structure returned will be written to *x. If neither x nor *x is NULL then an attempt is made to reuse the structure at *x (but see BUGS and EXAMPLES sections). Irrespective of the value of xa pointer to the structure is always returned (or NULL if an error occurred).

The PEM functions which write private keys take an enc parameter which specifies the encryption algorithm to use, encryption is done at the PEM level. If this parameter is set to NULL then the private key is written in unencrypted form.

The cb argument is the callback to use when querying for the pass phrase used for encrypted PEM structures (normally only private keys).

For the PEM write routines if the kstr parameter is not NULL then klen bytes at kstr are used as the passphrase and cb is ignored.

If the cb parameters is set to NULL and the u parameter is not NULL then the u parameter is interpreted as a null terminated string to use as the passphrase. If both cb and u are NULL then the default callback routine is used which will typically prompt for the passphrase on the current terminal with echoing turned off.

You'll likely only need something like this:

FILE *pemFile = fopen(...);
X509 *x509 = PEM_read_X509( pemFile, NULL, NULL, NULL );

Once you have the X509 certificate, you can useX509_get_pubkey() to get the RSA public key:

#include <openssl/x509.h>

EVP_PKEY *X509_get_pubkey(X509 *x);
EVP_PKEY *X509_get0_pubkey(const X509 *x);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM