下面是正在使用它的代码。
/* ---------------------------------------------------------- *
* These function calls initialize openssl for correct work. *
* ---------------------------------------------------------- */
OpenSSL_add_all_algorithms();
ERR_load_BIO_strings();
ERR_load_crypto_strings();
SSL_load_error_strings();
/* ---------------------------------------------------------- *
* Create the Input/Output BIO's. *
* ---------------------------------------------------------- */
certbio = BIO_new(BIO_s_file());
outbio = BIO_new_fp(stdout, BIO_NOCLOSE);
/* ---------------------------------------------------------- *
* initialize SSL library and register algorithms *
* ---------------------------------------------------------- */
if (SSL_library_init() < 0)
{
BIO_printf(outbio, "Could not initialize the OpenSSL library !\n");
}
/* ---------------------------------------------------------- *
* Set SSLv2 client hello, also announce SSLv3 and TLSv1 *
* ---------------------------------------------------------- */
method = TLSv1_client_method();
/* ---------------------------------------------------------- *
* Try to create a new SSL context *
* ---------------------------------------------------------- */
if ((ctx = SSL_CTX_new(method)) == NULL)
{
BIO_printf(outbio, "Unable to create a new SSL context structure.\n");
}
/* Create new SSL connection state object */
ssl = SSL_new(ctx);
/* Make the underlying TCP socket connection */
server = openconnection(ip_addr);
if (server != 0)
{
printf("Successfully made the TCP connection");
}
/* Attach the SSL session to the socket descriptor */
SSL_set_fd(ssl, server);
/**
* SSL_connect - initiate the TLS/SSL handshake with an TLS/SSL server
* Try to SSL-connect here, returns 1 for success
*/
err_status = SSL_connect(ssl);
if(err_status != 1)
{
err_status = SSL_get_error(ssl, err_status);
printf("SYSTEM:SSL_SOCKET:Could not build SSL session: %d %s\n", err_status,strerror(errno));
}
else
{
BIO_printf(outbio, "Successfully enabled SSL/TLS session");
}
/* Get the remote certificate into the X509 structure */
cert = SSL_get_peer_certificate(ssl);
if (cert == NULL)
{
BIO_printf(outbio, "Error: Could not get a certificate");
}
else
{
BIO_printf(outbio, "Retrieved the server's certificate");
}
/* ---------------------------------------------------------- *
* extract various certificate information *
* -----------------------------------------------------------*/
certname = X509_NAME_new();
certname = X509_get_subject_name(cert);
/* ---------------------------------------------------------- *
* display the cert subject here *
* -----------------------------------------------------------*/
BIO_printf(outbio, "Displaying the certificate subject data:\n");
X509_NAME_print_ex(outbio, certname, 0, 0);
BIO_printf(outbio, "\n");
SSL_free(ssl);
close(server);
X509_free(cert);
SSL_CTX_free(ctx);
BIO_printf(outbio, "Finished SSL/TLS connection with server");