Reputation: 11
I have a self-signature certificate in X509, and I need to parse the key in this certificate. I referred to the code of this website: https://zakird.com/2013/10/13/certificate-parsing-with-openssl
And in his parsing part, there are some grammar I can't use.
Like:
int pubkey_algonid = OBJ_obj2nid(cert->cert_info->key->algor->algorithm);
and:
rsa_key = pkey->pkey.rsa;
rsa_e_dec = BN_bn2dec(rsa_key->e);
rsa_n_hex = BN_bn2hex(rsa_key->n);
I can't use '->' to refer the struct internal variables. Am I need some files necessary ?
How do I solve it? Or is any other way to get the key in certificate?
Upvotes: 0
Views: 489
Reputation: 38771
You're referring to a website from 2013. Old versions of OpenSSL (and SSLeay before it) did allow access to fields in many structures (by declaring them publicly) including X509
(a typedef for struct x509_st
) for a cert, and RSA
for an RSA key(pair). Since 2016 it no longer does; this is called 'opaque' typing and is considered good style for a library which undergoes significant changes from time to time to avoid those changes causing crashes, corruption, and dangerously or even catastrophically wrong results in programs using the library. By making the interface 'opaque' internal changes either still work correctly, or if they can't, give an error message rather than undetected and possibly dangerous nonsense or undefined behavior.
Use X509_get_pubkey
or X509_get0_pubkey
to get the publickey as an EVP_PKEY
structure, from which
you can get the (already-converted) NID for the algorithm with EVP_PKEY_id
and
assuming the key is RSA get the RSA-specific structure with EVP_PKEY_get1_RSA
or EVP_PKEY_get0_RSA
, from which
you can get the n and e fields with RSA_get0_n
and RSA_get0_e
(or both at once with RSA_get0_key
).
The difference between get or get1 routines and get0 routines is that the former allocate a copy, which you should free using the appropriate routine when done to avoid a memory leak; the latter (get0) share existing memory and should not be freed, but must not be used if the thing they are sharing is freed or otherwise invalidated.
PS: the fact the cert is self-signed has no effect on parsing the publickey, although it can affect whether a system that does so is secure. But that's out of scope for SO.
Upvotes: 1