1

I have a client/server architecture in which I use the openssl library to implement an encrypted communication (TLSv1.2). Since I'm using "self signed" certificates, in order to verify server's identity, my idea is to put in the client side a physical copy of the server's public key (server_public_key.pem) and then verify if it is equals to which received in the handshake phase of TLS.

On the client, I can retrieve the latter with:

X509 *cert = SSL_get_peer_certificate(ssl);

Now, I would extract the human readable string of the public key contained in this object.

I know that I can print it in this way:

EVP_PKEY *pkey = X509_get_pubkey(cert);
PEM_write_PUBKEY(stdout, pkey);

But I need to keep it as a string (instead of send it to stdout). How can I do this ?

roalz
  • 2,699
  • 3
  • 25
  • 42
stackpic91
  • 189
  • 2
  • 4
  • 13

1 Answers1

1

Use BIO_new() to create a new BIO backed by an internal memory buffer (initially empty).

Then use PEM_write_bio_PUBKEY() to write the public key to the BIO, at which point use the functions documented in the BIO's manual page to retrieve the public key.

See the cited documentation for a simple example of creating a BIO, writing to it, then reading from it. Replacing the sample write operation with PEM_write_bio_PUBKEY() should be sufficient.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
  • I have another question. If I do "char buff[size];" and then "BIO_read(mem,buff,size)" where mem is the BIO object and "size" is the number of bytes to read, at the end of buff there are some strange characters. I think I'm doing some error in the memory allocation. Any suggestion ? Note that if I initialize buff in this way "char buff[]="" " I obtain this error: "*** stack smashing detected ***:" – stackpic91 Sep 14 '17 at 13:46
  • Solved. I forgot to insert 0 at the end of the buff ;) – stackpic91 Sep 14 '17 at 14:19