我尝试使用OpenSSL从我的嵌入式Linux设备建立SSL连接到自签名证书,这是我的代码:
/* Set up the library */
ERR_load_BIO_strings();
SSL_load_error_strings();
OpenSSL_add_all_algorithms();
/* Set up the SSL context */
m_ctx = SSL_CTX_new( TLSv1_method());
/* Load the trust store */
if(! SSL_CTX_load_verify_locations(m_ctx, "../certificate.pem", NULL))
{
fprintf(stderr, "Error loading trust store\n");
ERR_print_errors_fp(stderr);
SSL_CTX_free(m_ctx);
return FALSE;
}
/* Setup the connection */
m_bio = BIO_new_ssl_connect(m_ctx);
/* Set the SSL_MODE_AUTO_RETRY flag */
BIO_get_ssl(m_bio, & m_ssl);
SSL_set_mode(m_ssl, SSL_MODE_AUTO_RETRY);
/* Create and setup the connection */
BIO_set_conn_hostname(m_bio, (QString( serverAddress) + ":"+QString::number(serverPort)).toAscii().constData() );
if(BIO_do_connect(m_bio) <= 0)
{
fprintf(stderr, "Error attempting to connect\n");
ERR_print_errors_fp(stderr);
BIO_free_all(m_bio);
SSL_CTX_free(m_ctx);
IsConnected = false;
return FALSE;
}
SSL_get_peer_certificate(m_ssl);
/* Check the certificate */
if(SSL_get_verify_result(m_ssl) != X509_V_OK)
{
fprintf(stderr, "Certificate verification error: %ld\n", SSL_get_verify_result(m_ssl));
BIO_free_all(m_bio);
SSL_CTX_free(m_ctx);
return FALSE;
}
上面的代码已成功连接到服务器,但SSL_get_verify_result
函数返回error:18
表示:
18 X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: self signed certificate
the passed certificate is self-signed and the same certificate cannot
be found in the list of trusted
此外,我可以通过Web浏览器检查服务器,并通过我的嵌入式Linux OpenSSL命令连接服务器:
openssl s_client -connect hostIP:443 -tls1
它们都已连接并成功显示内容,我完全混淆了SSL_get_verify_result
无法验证的原因,而网络浏览器和OpenSSL命令行都没问题。
另外,命令行中的Webroster和OpenSSL如何不需要加载证书文件(我猜他们收到了它),而在我的代码中,我需要通过
引入证书文件SSL_CTX_load_verify_locations(m_ctx, "../certificate.pem", NULL)
另外,我从Firefox导出主机的证书文件并使用此文件提供我的代码,但同样结果! Firefox如何使用此文件,但我的代码无法使用?
修改 问题是因为服务器和cilent中的时间设置不同,实际上服务器时间设置是客户端日期+ 1,然后当服务器创建证书时,它的beginOn参数设置为3,5,2018,而客户端日期是3,4,2018。实际上openssl命令行显示有关此事的一些错误,但我不在乎。但我不知道为什么firefox完全忽略beginOn并且工作正常,为什么SSL_get_verify_result没有返回正确的错误代码?谢谢大家的指导。< / p>