//创建一个安全的链接,需要证书
bool CSSLConnect::ConnectSSL(const char* pUrl, int nPort, int nCreType, const char* pCerFile, const char* pPassword, const char* pCmd)
{
char szURL[SSL_BUFF_200] = {'\0'};
sprint_safe(szURL, SSL_BUFF_200, "%s:%d", pUrl, nPort);
Close();
//初始化SSLCtx
//m_pSSLCtx = SSL_CTX_new(SSLv23_client_method());
m_pSSLCtx = SSL_CTX_new(TLSv1_client_method());
if(m_pSSLCtx == NULL)
{
printf("SSL CTX new Fail.\n");
return false;
}
SSL_CTX_set_options(m_pSSLCtx, SSL_OP_ALL);
//解析证书文件
BIO* pKeyBuff = BIO_new_file(pCerFile, "r");
if(NULL == pKeyBuff)
{
printf("[CSSLConnect::Connect]Load key file Fail.\n");
return false;
}
X509* pX509 = NULL;
EVP_PKEY* pPKey = NULL;
pX509 = LoadBaseCret(pKeyBuff, nCreType, pPassword);
if(NULL == pX509)
{
printf("[CSSLConnect::Connect]LoadBaseCret error.\n");
BIO_free_all(pKeyBuff);
return false;
}
//加载证书
//if(1 != SSL_CTX_use_certificate(m_pSSLCtx, pX509))
if(1 != SSL_CTX_add_client_CA(m_pSSLCtx, pX509))
{
ERR_error_string(ERR_get_error(), (char* )m_szError);
printf("[CSSLConnect::Connect] SSL_CTX_use_certificate ERROR: %s.\n", m_szError);
return false;
}
/*
//测试代码
if(! SSL_CTX_load_verify_locations(m_pSSLCtx, "dev.pem", NULL))
{
//没有正确的获得pem
ERR_error_string(ERR_get_error(), (char* )m_szError);
printf("[CSSLConnect::Connect] pSockBIO ERROR: %s.\n", m_szError);
return false;
}
if(1 != SSL_CTX_use_certificate_file(m_pSSLCtx, "dev.pem", SSL_FILETYPE_PEM))
{
//没有正确的获得pem
ERR_error_string(ERR_get_error(), (char* )m_szError);
printf("[CSSLConnect::Connect] pSockBIO ERROR: %s.\n", m_szError);
return false;
}
*/
//检查证书是否有效
m_pSockBIO = BIO_new_ssl_connect(m_pSSLCtx);
if(m_pSockBIO == NULL)
{
//没有正确的获得BIO
ERR_error_string(ERR_get_error(), (char* )m_szError);
printf("[CSSLConnect::Connect] pSockBIO ERROR: %s.\n", m_szError);
return false;
}
BIO_get_ssl(m_pSockBIO, &m_pSSL);
if(m_pSSL == NULL)
{
//没有正确的获得BIO
ERR_error_string(ERR_get_error(), (char* )m_szError);
printf("[CSSLConnect::Connect] m_pSSL ERROR: %s.\n", m_szError);
return false;
}
if(SSL_get_verify_result(m_pSSL) != X509_V_OK)
{
//X509证书无效
ERR_error_string(ERR_get_error(), (char* )m_szError);
printf("[CSSLConnect::Connect] SSL_get_verify_result ERROR: %s.\n", m_szError);
return false;
}
SSL_set_mode(m_pSSL, SSL_MODE_AUTO_RETRY);
BIO_set_conn_hostname(m_pSockBIO, szURL);
int nRet = BIO_do_connect(m_pSockBIO);
if(nRet <= 0)
{
//没有正确连接
ERR_error_string(ERR_get_error(), (char* )m_szError);
printf("[CSSLConnect::Connect] pSockBIO Connect ERROR: %s.\n", m_szError);
return false;
}
int nPos = 0;
int nCmdLen = (int)strlen(pCmd);
while(true)
{
if(nPos == nCmdLen || nCmdLen == 0)
{
break;
}
int nLen = BIO_write(m_pSockBIO, &pCmd[nPos], nCmdLen);
if(nLen <= 0)
{
break;
}
else
{
nPos += nLen;
nCmdLen -= nPos;
}
}
char szData[SSL_BUFF_1024] = {'\0'};
m_strBuff = "";
while(true)
{
int nLen = BIO_read(m_pSockBIO, szData, SSL_BUFF_1024);
if(nLen <= 0)
{
break;
}
else
{
m_strBuff += szData;
}
}
BIO_free_all(pKeyBuff);
X509_free(pX509);
return true;
}