#define HOST_NAME "www.random.org"
#define HOST_PORT "443"
#define HOST_RESOURCE "/cgi-bin/randbyte?nbytes=32&format=h"
long res = 1;
SSL_CTX* ctx = NULL;
BIO *web = NULL, *out = NULL;
SSL *ssl = NULL;
const long flags = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION;
const char* const PREFERRED_CIPHERS = "HIGH:!aNULL:!kRSA:!PSK:!SRP:!MD5:!RC4";
SSL_library_init();
SSL_load_error_strings();
OPENSSL_config(NULL);
// 初始化
const SSL_METHOD* method = SSLv23_method();
ctx = SSL_CTX_new(method);
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, verify_callback);
SSL_CTX_set_verify_depth(ctx, 4);
SSL_CTX_set_options(ctx, flags);
SSL_CTX_load_verify_locations(ctx, "random-org-chain.pem", NULL);
BIO_new_ssl_connect(ctx);
BIO_set_conn_hostname(web, HOST_NAME ":" HOST_PORT);
BIO_get_ssl(web, &ssl);
if(!(ssl != NULL))
handleFailure();
SSL_set_cipher_list(ssl, PREFERRED_CIPHERS);
res = SSL_set_tlsext_host_name(ssl, HOST_NAME);
if(!(1 == res))
handleFailure();
BIO_new_fp(stdout, BIO_NOCLOSE);
res = BIO_do_connect(web);
if(!(1 == res)) handleFailure();
res = BIO_do_handshake(web);
if(!(1 == res))
handleFailure();
// 证书校验
X509* cert = SSL_get_peer_certificate(ssl);
if(cert)
X509_free(cert);
if(NULL == cert)
handleFailure();
res = SSL_get_verify_result(ssl);
if(!(X509_V_OK == res))
handleFailure();
// 通信
BIO_puts(web, "GET " HOST_RESOURCE " HTTP/1.1\r\n"
"Host: " HOST_NAME "\r\n"
"Connection: close\r\n\r\n");
BIO_puts(out, "\n");
int len = 0;
do
{
char buff[1536] = {};
len = BIO_read(web, buff, sizeof(buff));
if(len > 0)
BIO_write(out, buff, len);
} while (len > 0 || BIO_should_retry(web));
if(out)
BIO_free(out);
if(web != NULL)
BIO_free_all(web);
if(NULL != ctx)
SSL_CTX_free(ctx);
网友评论