这是我创建的一个简约程序,它连接到服务器并将其 ssl 证书打印到标准输出。希望它能帮助其他人解决类似的问题:
#ifdef WIN32
#include <windows.h>
#include <winsock2.h>
#else
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#endif
#include <openssl/ssl.h>
#include <cstdlib>
#include <iostream>
static const char *host= "10.23.10.12";
static int port=443;
int tcp_connect(const char *host,int port)
{
#ifdef WIN32
WSADATA wsaData;
WORD version;
int error;
version = MAKEWORD( 2, 0 );
error = WSAStartup( version, &wsaData );
/* check for error */
if ( error != 0 )
{
/* error occured */
return -1;
}
/* check for correct version */
if ( LOBYTE( wsaData.wVersion ) != 2 ||
HIBYTE( wsaData.wVersion ) != 0 )
{
/* incorrect WinSock version */
WSACleanup();
return -1;
}
/* WinSock has been initialized */
#endif
struct hostent *hp;
struct sockaddr_in addr;
int sock;
if(!(hp=gethostbyname(host)))
printf("Couldn't resolve host");
memset(&addr,0,sizeof(addr));
addr.sin_addr=*(struct in_addr*)
hp->h_addr_list[0];
addr.sin_family=AF_INET;
addr.sin_port=htons(port);
if((sock=(int)socket(AF_INET,SOCK_STREAM,
IPPROTO_TCP))<0)
printf("Couldn't create socket");
if(connect(sock,(struct sockaddr *)&addr,
sizeof(addr))<0)
printf("Couldn't connect socket");
return sock;
}
int main(int argc,char **argv)
{
SSL_CTX *ctx;
SSL *ssl;
BIO *sbio;
int sock;
SSL_METHOD *meth=NULL;
meth=SSLv23_client_method();
OpenSSL_add_ssl_algorithms();
SSL_load_error_strings();
ctx=SSL_CTX_new(meth);
/* Connect the TCP socket*/
sock=tcp_connect(host,port);
/* Connect the SSL socket */
ssl=SSL_new(ctx);
sbio=BIO_new_socket(sock,BIO_NOCLOSE);
SSL_set_bio(ssl,sbio,sbio);
if(SSL_connect(ssl)<=0)
printf("SSL connect error");
X509 *peer;
peer=SSL_get_peer_certificate(ssl);
PEM_write_X509(stdout, peer);
SSL_CTX_free(ctx);
close(sock);
#ifdef WIN32
closesocket(sock);
WSACleanup();
#else
close(sock);
#endif
exit(0);
}
代码是本文所建议的示例的修改版本。
编辑:我一直收到错误 OPENSSL_UPLINK: no OPENSSL_APPLINK on windows。在互联网上进行了大量搜索后,我找到了这篇文章并将其添加到我的代码中:
extern "C" {
#include <openssl/applink.c>
}
似乎这是一些解决方法,以避免对编译器和运行时选项兼容性的要求。