从证书生成,到QSslSocket 等类的应用

来源:互联网 发布:centos安装nodejs 编辑:程序博客网 时间:2024/06/05 19:37
Ssl 相关背景知识:

CA,X509标准等,可自行搜索.网上也挺多的.

下面三点来自网络,可以对后面的QSslSocket编程有个感性认识.

1. 信息内容加密

接收者的公钥:用于加密

接收者的私钥:用于解密

--------验证接收者(保证数据私密性)

2. 数字签名

发送者的私钥:用于加密

发送者的公钥:用于解密

--------验证发送者(保证不可抵赖性、数据完整性)

3. 证书

用于确认公钥所对应的私钥持有者的身份

证书与公共密钥相关联

证书内容包括:证书的名称(含国家,,城市,组织等信息),公匙;认证机构的名称,签名;有效时间;证书签发的流水号等信息.

证书的概念:首先要有一个根证书,然后用根证书来签发用户证书。

对于申请证书的用户:在生成证书之前,一般会有一个私钥,然后用私钥生成证书请求(证书请求里应含有公钥信息),再利用证书服务器的根证书来签发证书。

特别的:

1)自签名证书(一般用于顶级证书、根证书):证书的名称和认证机构的名称相同.

2)根证书:根证书是CA认证中心给自己颁发的证书,是信任链的起始点。安装根证书意味着对这个CA认证中心的信任

数字证书则是由证书认证机构(CA)对证书申请者真实身份验证之后,用CA的根证书对申请人的一些基本信息以及申请人的公钥进行签名(相当于加盖发证书机构的公章)后形成的一个数字文件。数字证书包含证书中所标识的实体的公钥(就是说你的证书里有你的公钥),由于证书将公钥与特定的个人匹配,并且该证书的真实性由颁发机构保证(就是说可以让大家相信你的证书是真的),因此,数字证书为如何找到用户的公钥并知道它是否有效这一问题提供了解决方案。





Qt 文档对QSslSocket 的简介(读者可以看英文原文,但实际应用中有些地方跟文档里描述的有点不一样

,下面这些会加一点鄙人实践之后的经验):

QSslSocket 在Qt4.3引进。 

        QSslSocket 类为服务端和客户端提供了SSL加密套接字. 

你可以使用 QSslSocket 建立的一个安全的,加密的 TCP  连接去传输加密数据.

它可以工作在服务器模式和客户端模式。以及它支持最新的SSL协议,包括 SSLv3 和 TLSvxx (到了Qt 5.2.0已经支持多个TLS版本).

QSslSocket 默认使用 SSLv3 ,你可以在握手之前调用 setProtocol() 去改变 SSL 协议.

         SSL 运行于已进入连接状态的TCP流之上. 使用 QSslSocket 有两种简单的方法建立安全连接.

1.通过直接 SSL 握手。

2.延迟 SSL 握手,延迟 SSL  握手发生在连接已经建立在非加密模式之后.


通常的方法是使用 QSslSocket 构造一个对象通过调用其 connectToHostEncrypted() 来开始一个安全连接.

下面这个方案是当连接已经建立时开始的直接握手。

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. QSslSocket *socket = new QSslSocket(this);  
  2.  connect(socket, SIGNAL(encrypted()), this, SLOT(ready()));  
  3.   
  4.  socket->connectToHostEncrypted("imap.example.com", 993);  


延迟握手可以在调用连接函数后,根据是服务端还是客户端调用下面两个函数中的一个:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. socket->startClientEncryption();  
  2. socket->startServerEncryption();  

        就像一个普通的 QTcpSocket, QSslSocket 进入 HostLookupState(主机查找), ConnectingState(连接中状态),最后是 ConnectedState(已连接状态),

如果连接成功,握手会自动开始,如果握手成功, encrypted() 信号会被发出,以指明这个套接字已经进入加密状态以供使用。

      注意,当connectToHostEncrypted()函数返回后(encrypted()信号发射之前),就可以马上向套接字写数据了,这些数据在会被保存在套接字的队列中,直到 encrypted()信号被发射.


    一个使用延迟SSL握手去加密一个存在的连接例子,这个例子是一个 SSL  server 加密一个新进入的连接. 假设你创建了一个 SSL server 作为QTcpServer 的子

类. 你要重载 QTcpServer:;incomingConnection() 和一些其它的东西,就像后面这个例子一样. 首先构造一个 QSslSocket 实例,并调用其 setSocketDescriptor()

去设置这个新的套接字的描述符为新传进来的套接字描述符.然后通过调用 starServerEncryption()  初始化 SSL 握手.

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. void SslServer::incomingConnection(int socketDescriptor)  
  2.  {  
  3.      QSslSocket *serverSocket = new QSslSocket;  
  4.      if (serverSocket->setSocketDescriptor(socketDescriptor)) {  
  5.          connect(serverSocket, SIGNAL(encrypted()), this, SLOT(ready()));  
  6.          serverSocket->startServerEncryption();  
  7.      } else {  
  8.          delete serverSocket;  
  9.      }  
  10.  }  


     如果发生错误,QSslSocket 会发射 sslErrors() 信号. 在这个例子里,如果没有执行忽略错误的动作,一旦发生错误,这个连接会被丢弃(droped). 继续,如果要无视所发生的错误,你可以调用 ignoreSslErrors(),可以在以下情况去调用 ignoreSslErrors()

1. 错误发生后,在这个incomingConnection() 这个槽里,或连接 void    sslErrors ( const QList<QSslError> & errors ) 信号的槽里。

2.在构造 QSslSocket 之后,尝试连接之前的任何时刻。

这样会允许QSslSocket 忽视与对端建立认证时所遇到的错误. 在SSL握手期间忽视错误一定要谨慎。

一个安全连接的基本特征就是必须建立了一个成功的握手(此握手,不是TCP连接时所进行的握手,而是建立安全认证时所进行的握手)。

3. 注意:如果你在连接前通过调用了带参的 void QSslSocket::ignoreSslErrors ( const QList<QSslError> & errors ), sslErrors()信号还是会被发射的.

只是连接会成功。


        一旦加密后,你可以将QSslSocket 当做正常的 QTcpSocket 来使用。当 readyRead() 信号被发射时,你可以调用 read(), canReadLine() 和 readLine(),

或者 getChar() 从 QSslSocket 的内部缓冲区读取加密数据。 并且你可以调用 write() 或者 putChar() 向对端写数据. QSslSocket 会自动为你所写入的数据进行加密,并在

数据已经写入到对端时会发出 encryptedBytesWritten() 信号.

 

       为方便起见,QSslSocket 支持 QTcpSocket 的阻塞函数, waitForConnected(), waitForReadyRead(), waitForBytesWritten(), 和 waitForDisconnected(). 同时也提供 .

waitForEncrypted(), waitForEncrypted()在加密连接建立之前会阻塞当前的调用线程.

waitForBytesWritten(),如果在连接调用写函数的话,如果你的数据字节流顺序对不上,建议调用这个函数.

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. QSslSocket socket;  
  2.  socket.connectToHostEncrypted("http.example.com", 443);  
  3.  if (!socket.waitForEncrypted()) {  
  4.      qDebug() << socket.errorString();  
  5.      return false;  
  6.  }  
  7.   
  8.  socket.write("GET / HTTP/1.0\r\n\r\n");  
  9.  while (socket.waitForReadyRead())  
  10.      qDebug() << socket.readAll().data();  





QSslSocket 提供了一个延伸, 易用的处理加密用的密码,私钥,本地,对端,认证机构证书(CA certificattes)的 API,也提供了处理握手阶段所发生的错误的API.


下面这些功能也可以被定制:

1. 套接字的加密通信套件可以在握手前通过 setCiphers() 和 setDefaultCiphers().定制.

2. 套接字的本地证书和私钥可以在握手前通过 setLocalCertificate() 和 setPrivateKey()定制.

3. CA证书数据库可以被扩展和定制,可通过这些函数定制,addCaCertificate(), addCaCertificates(), setCaCertificates(), addDefaultCaCertificate(),addDefaultCaCertificates和 setDefaultCaCertificates().


关于密码和证书的更多信息,请参照 QSslCipher 和 QSslCertificate.

注: 要知道bytesWritten() 与 encryptedBytesWritten() 这两个信号之间的不同. 对于 QTcpSocket, bytesWritten() 信号在数据一写入TCP套接字时会马上被发射.对于 QSslSocket, bytesWritten() 会在数据正在加密时发射. 当数据加密后写入到TCP套接字时encryptedBytesWritten()会被发射.



鄙人实践代码:

实践环境: Fedora19 , Qt4.8.5 ,Qt5.2.0(Qt5.2.0,有变化,代码要改动一些),OpenSsl(Fedora 更新到什么版本就是什么版本了)

整个例子,是结合简单的服务端多线程来写的,开启服务端后,可开启多个客户端进行测试.



服务器端(为了简化例子,有一些汲及鄙人自己的东西没有贴上来):

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #ifndef SERVER_H  
  2. #define SERVER_H  
  3. #include "include/common/net_heads.h"  
  4. #include <QTcpServer>  
  5. #include <QSslSocket>  
  6. #include <QSslCipher>  
  7. #include <QMutex>  
  8. #include <QMutexLocker>  
  9.   
  10. class ServerThread;  
  11. class Server : public QTcpServer  
  12. {  
  13.     Q_OBJECT  
  14. public:  
  15.     Server(QObject *parent = 0);  
  16. public slots:  
  17.     void startService();  
  18.     void stopService();  
  19. signals:  
  20.   
  21. private slots:  
  22.     void debugMsgThreadDestory();  
  23.     void debugMsgThreadFinished();  
  24.     void serverThreadDisconnected(int initSocketDescriptor);  
  25. protected:  
  26.     void incomingConnection(int socketDescriptor);  
  27.   
  28. private:  
  29.     QList<ServerThread *> serverThreadList;  
  30.     QMutex threadListLock;  
  31. };  
  32. #endif // SERVER_H  

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #include "server.h"  
  2. #include "serverthread.h"  
  3. #include <stdlib.h>  
  4. #include "include/debug/debug.h"  
  5. Server::Server(QObject *parent)  
  6.     : QTcpServer(parent)  
  7. {  
  8.     /*设置socket的默认ca数据库*/  
  9.     QList<QSslCertificate> caCertList = QSslCertificate::fromPath("../certificates/cacert.pem");  
  10.     QSslSocket::setDefaultCaCertificates(caCertList);  
  11. }  
  12.   
  13. void Server::startService()  
  14. {  
  15.     listen(QHostAddress::Any,TCP_PORT);  
  16.     PrintMsg("listening...");  
  17. }  
  18.   
  19. void Server::stopService()  
  20. {  
  21.     close();  
  22. }  
  23.   
  24. void Server::incomingConnection(int socketDescriptor)  
  25. {  
  26.     ServerThread *thread = new ServerThread(socketDescriptor);  
  27.     connect(thread, SIGNAL(socketDisconnected(int)), this, SLOT(serverThreadDisconnected(int)),Qt::QueuedConnection);  
  28.     connect(thread,SIGNAL(finished()),this,SLOT(debugMsgThreadFinished()));  
  29.     connect(thread,SIGNAL(destroyed()),this,SLOT(debugMsgThreadDestory()));  
  30.   
  31.   
  32.     threadListLock.lock();  
  33.     serverThreadList.append(thread);  
  34.     threadListLock.unlock();  
  35.     thread->start();  
  36. }  
  37.   
  38. void Server::serverThreadDisconnected(int initSocketDescriptor)  
  39. {  
  40.     QMutexLocker lock(&threadListLock);  
  41.     Q_UNUSED(lock)  
  42.     for(int i = 0; i < serverThreadList.count(); i++)  
  43.     {    
  44.         if(serverThreadList.at(i)->getInitSocketDescriptor() == initSocketDescriptor)  
  45.         {  
  46.             PrintMsg("serverThreadList.at(%d)->getSocketDescriptor() = %d",i,serverThreadList.at(i)->getSocketDescriptor());  
  47.             serverThreadList.at(i)->wait();  
  48.             delete serverThreadList.at(i);  
  49.             serverThreadList.removeAt(i);  
  50.             PrintMsg("serverThreadList.removeAt(%d) initSocketDescriptor = %d list count = %d",i,initSocketDescriptor,serverThreadList.count());  
  51.             return;  
  52.         }  
  53.     }  
  54.     return;  
  55. }  
  56.   
  57. void Server::debugMsgThreadDestory()  
  58. {  
  59.     //PrintMsg("thread destory.");  
  60. }  
  61.   
  62. void Server::debugMsgThreadFinished()  
  63. {  
  64.     //PrintMsg("thread finished.");  
  65. }  


[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #ifndef SERVERTHREAD_H  
  2. #define SERVERTHREAD_H  
  3. #include <QThread>  
  4. #include <QSslSocket>  
  5. #include <QSslCipher>  
  6. #include <QTimer>  
  7. class ServerThread : public QThread  
  8. {  
  9.     Q_OBJECT  
  10. public:  
  11.     ServerThread(int socketDescriptor, QObject *parent = 0);  
  12.     ~ServerThread();  
  13.     int getSocketDescriptor() const;  
  14.     int getInitSocketDescriptor() const;  
  15. protected:  
  16.     void run();  
  17.   
  18. private slots:  
  19.     void _run();  
  20.     void datareceive();  
  21.     void handleSocketEncrypted();  
  22.     void handleSslModeChanged(QSslSocket::SslMode mode);  
  23.     void handleSocketConnected();  
  24.     void handleSocketDisconnected();  
  25.     void handleSockStateChange(const QAbstractSocket::SocketState &socketState);  
  26.   
  27.     void handleSocketError(const QAbstractSocket::SocketError &socketError);  
  28.     void handleSslErrorList(const QList<QSslError> &errorList);  
  29.     void handlePeerVerifyError(const QSslError &error);  
  30.     void handleSslError(const QSslError &error);  
  31.   
  32. private:  
  33.     void requestDestroyed();  
  34. signals:  
  35.     void socketDisconnected(int initDescriptor);  
  36. private:  
  37.     int socketDescriptor;  
  38.     QSslSocket *socket;  
  39.     QTimer *runTimer;  
  40. };  
  41.   
  42. #endif // SERVERTHREAD_H  

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #include "serverthread.h"  
  2. #include "include/debug/debug.h"  
  3. #include "getsslrelateinfo.h"  
  4. #include "crccheck.h"  
  5. #include "datatype.h"  
  6. #include "datatransfer.h"  
  7. ServerThread::ServerThread(int socketDescriptor, QObject *parent) : QThread(parent), socketDescriptor(socketDescriptor)  
  8. {  
  9.     socket = new QSslSocket(this);  
  10.     runTimer = new QTimer(this);  
  11.     moveToThread(this);  
  12. }  
  13.   
  14. ServerThread::~ServerThread()  
  15. {  
  16. }  
  17.   
  18. int ServerThread::getSocketDescriptor() const  
  19. {  
  20.     if(socket)  
  21.         return socket->socketDescriptor();  
  22.     return -1;  
  23. }  
  24.   
  25. int ServerThread::getInitSocketDescriptor() const  
  26. {  
  27.     return socketDescriptor;  
  28. }  
  29.   
  30. void ServerThread::run()  
  31. {  
  32.     if (!socket->setSocketDescriptor(socketDescriptor)) {  
  33.         PrintMsg("socket->setSocketDescriptor %s",socket->errorString().toAscii().data());  
  34.         handleSocketDisconnected();  
  35.         return;  
  36.     }   
  37.   
  38. #if 1 /*如果不设定证书和私钥,连接会失败,并不像官方所说那样,可以按不加密方式使用*/  
  39.     socket->setPrivateKey("../certificates/server.pem");  
  40.     socket->setLocalCertificate("../certificates/server.crt");  
  41. #else //for test, self signed certificates  
  42.     socket->setPrivateKey("test_certificates/server.key");  
  43.     socket->setLocalCertificate("test_certificates/server.csr");  
  44.   
  45.     //socket->setPrivateKey("test_certificates/serverlo.key");  
  46.     //socket->setLocalCertificate("test_certificates/serverlo.csr");  
  47. #endif  
  48.   
  49.     socket->setPeerVerifyMode(QSslSocket::VerifyPeer);  
  50.   
  51.     connect(socket,SIGNAL(readyRead()),this,SLOT(datareceive()));  
  52.     connect(socket,SIGNAL(encrypted()),this,SLOT(handleSocketEncrypted()));  
  53.     connect(socket,SIGNAL(modeChanged(QSslSocket::SslMode)),this,SLOT(handleSslModeChanged(QSslSocket::SslMode)));  
  54.     connect(socket,SIGNAL(connected()),this,SLOT(handleSocketConnected()));  
  55.     connect(socket,SIGNAL(disconnected()),this,SLOT(handleSocketDisconnected()));  
  56.     connect(socket,SIGNAL(stateChanged(QAbstractSocket::SocketState)),this,SLOT(handleSockStateChange(QAbstractSocket::SocketState)));  
  57.     connect(socket,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(handleSocketError(QAbstractSocket::SocketError)));  
  58.     connect(socket,SIGNAL(sslErrors(QList<QSslError>)),this,SLOT(handleSslErrorList(QList<QSslError>)),Qt::DirectConnection);  
  59.     connect(socket,SIGNAL(peerVerifyError(QSslError)),this,SLOT(handlePeerVerifyError(QSslError)));  
  60.     socket->startServerEncryption();  
  61.     runTimer->setInterval(1000);  
  62.     runTimer->setSingleShot(true);  
  63.     connect(runTimer,SIGNAL(timeout()),this,SLOT(_run()));  
  64.     runTimer->start();  
  65.     PrintMsg("socket Mode: %d",socket->mode());  
  66.     exec();  
  67. }  
  68.   
  69. void ServerThread::_run()  
  70. {  
  71.   
  72.     if(socket->isEncrypted())  
  73.     {  
  74.         QString str = QString("hello I am Server threadId: %1").arg(QThread::currentThreadId());  
  75.         QByteArray block;  
  76.         block.resize(str.length() + 1);  
  77.         memcpy(block.data(),str.toLocal8Bit().data(),block.size());  
  78.         socket->write(block);  
  79.     }  
  80.     runTimer->start();  
  81. }  
  82.   
  83. void ServerThread::datareceive()  
  84. {  
  85.     while(socket->bytesAvailable() > 0 )  
  86.     {  
  87.         QByteArray datagram;  
  88.         datagram.resize(socket->bytesAvailable());  
  89.         socket->read(datagram.data(),datagram.size());  
  90.         qDebug() << "thread:" << QThread::currentThreadId() << datagram;  
  91.     }  
  92. }  
  93.   
  94. void ServerThread::handleSocketEncrypted()  
  95. {  
  96.     PrintMsg("handleSocketEncrypted.");  
  97. }  
  98.   
  99. void ServerThread::handleSslModeChanged(QSslSocket::SslMode mode)  
  100. {  
  101.     PrintMsg("socket Mode Change: %d",mode);  
  102. }  
  103.   
  104. void ServerThread::handleSocketConnected()  
  105. {  
  106.     PrintMsg("Socket Connected");  
  107. }  
  108.   
  109. void ServerThread::handleSocketDisconnected()  
  110. {  
  111.     PrintMsg("Socket Disconnected");  
  112.     runTimer->stop();  
  113.     requestDestroyed();  
  114. }  
  115.   
  116. void ServerThread::requestDestroyed()  
  117. {  
  118.     PrintMsg("requestDestroyed.bytesToWrite %lld",socket->bytesToWrite());  
  119.     if(socket->isOpen())  
  120.         socket->close();  
  121.     quit();  
  122.     emit socketDisconnected(socketDescriptor);  
  123. }  
  124.   
  125.   
  126.   
  127. void ServerThread::handleSocketError(const QAbstractSocket::SocketError &socketError)  
  128. {  
  129.     PrintMsg("================socket error=================");  
  130.     switch(socketError)  
  131.     {  
  132.     case QAbstractSocket::ConnectionRefusedError:  
  133.         PrintMsg("The connection was refused by the peer (or timed out).");  
  134.         break;  
  135.     case QAbstractSocket::RemoteHostClosedError:  
  136.         PrintMsg("The remote host closed the connection. Note that the client socket (i.e., this socket) will be closed after the remote close notification has been sent.");  
  137.         break;  
  138.     case QAbstractSocket::HostNotFoundError:  
  139.         PrintMsg("The host address was not found.");  
  140.         break;  
  141.     case QAbstractSocket::SocketAccessError:  
  142.         PrintMsg("The socket operation failed because the application lacked the required privileges.");  
  143.         break;  
  144.     case QAbstractSocket::SocketResourceError:  
  145.         PrintMsg("The local system ran out of resources (e.g., too many sockets).");  
  146.         break;  
  147.     case QAbstractSocket::SocketTimeoutError:  
  148.         PrintMsg("The socket operation timed out.");  
  149.         break;  
  150.     case QAbstractSocket::DatagramTooLargeError:  
  151.         PrintMsg("The datagram was larger than the operating system's limit (which can be as low as 8192 bytes).");  
  152.         break;  
  153.     case QAbstractSocket::NetworkError:  
  154.         PrintMsg("An error occurred with the network (e.g., the network cable was accidentally plugged out).");  
  155.         break;  
  156.     case QAbstractSocket::AddressInUseError:  
  157.         PrintMsg("The address specified to bind() is already in use and was set to be exclusive.");  
  158.         break;  
  159.     case QAbstractSocket::SocketAddressNotAvailableError:  
  160.         PrintMsg("The address specified to bind() does not belong to the host.");  
  161.         break;  
  162.     case QAbstractSocket::UnsupportedSocketOperationError:  
  163.         PrintMsg("The requested socket operation is not supported by the local operating system (e.g., lack of IPv6 support).");  
  164.         break;  
  165.     case QAbstractSocket::ProxyAuthenticationRequiredError:  
  166.         PrintMsg("The socket is using a proxy, and the proxy requires authentication.");  
  167.         break;  
  168.     case QAbstractSocket::SslHandshakeFailedError:  
  169.         PrintMsg("The SSL/TLS handshake failed, so the connection was closed (only used in SslSocket)");  
  170.         break;  
  171.     case QAbstractSocket::UnfinishedSocketOperationError:  
  172.         PrintMsg("Used by AbstractSocketEngine only, The last operation attempted has not finished yet (still in progress in the background).");  
  173.         break;  
  174.     case QAbstractSocket::ProxyConnectionRefusedError:  
  175.         PrintMsg("Could not contact the proxy server because the connection to that server was denied");  
  176.         break;  
  177.     case QAbstractSocket::ProxyConnectionClosedError:  
  178.         PrintMsg("The connection to the proxy server was closed unexpectedly (before the connection to the final peer was established)");  
  179.         break;  
  180.     case QAbstractSocket::ProxyConnectionTimeoutError:  
  181.         PrintMsg("The connection to the proxy server timed out or the proxy server stopped responding in the authentication phase.");  
  182.         break;  
  183.     case QAbstractSocket::ProxyNotFoundError:  
  184.         PrintMsg("The proxy address set with setProxy() (or the application proxy) was not found.");  
  185.         break;  
  186.     case QAbstractSocket::ProxyProtocolError:  
  187.         PrintMsg("The connection negotiation with the proxy server because the response from the proxy server could not be understood.");  
  188.         break;  
  189.     case QAbstractSocket::UnknownSocketError:  
  190.         PrintMsg("An unidentified error occurred.");  
  191.         break;  
  192.     default:  
  193.         PrintMsg("Not match any errors.");  
  194.         break;  
  195.     }  
  196. }  
  197.   
  198. void ServerThread::handleSslErrorList(const QList<QSslError> &errorList)  
  199. {  
  200.     PrintMsg("====================Ssl Error List==================");  
  201.     for(int i = 0 ;i < errorList.count(); i++)  
  202.     {  
  203.         QSslError SslError = errorList.at(i);  
  204.         handleSslError(SslError);  
  205.     }  
  206. }  
  207.   
  208. void ServerThread::handlePeerVerifyError(const QSslError &error)  
  209. {  
  210.     handleSslError(error);  
  211. }  
  212.   
  213. void ServerThread::handleSslError(const QSslError & error)  
  214. {  
  215.     PrintMsg("====================Ssl Error==================");  
  216.     PrintMsg("%s",error.errorString().toAscii().data());  
  217.     switch(error.error())  
  218.     {  
  219.     case QSslError::NoError:  
  220.         break;  
  221.     case QSslError::UnableToGetIssuerCertificate:  
  222.         break;  
  223.     case QSslError::UnableToDecryptCertificateSignature:  
  224.         break;  
  225.     case QSslError::UnableToDecodeIssuerPublicKey:  
  226.         break;  
  227.     case QSslError::CertificateSignatureFailed:  
  228.         break;  
  229.     case QSslError::CertificateNotYetValid:  
  230.         break;  
  231.     case QSslError::CertificateExpired:  
  232.         break;  
  233.     case QSslError::InvalidNotBeforeField:  
  234.         break;  
  235.     case QSslError::InvalidNotAfterField:  
  236.         break;  
  237.     case QSslError::SelfSignedCertificate:  
  238.         break;  
  239.     case QSslError::SelfSignedCertificateInChain:  
  240.         break;  
  241.     case QSslError::UnableToGetLocalIssuerCertificate:  
  242.         break;  
  243.     case QSslError::UnableToVerifyFirstCertificate:  
  244.         break;  
  245.     case QSslError::CertificateRevoked:  
  246.         break;  
  247.     case QSslError::InvalidCaCertificate:  
  248.         break;  
  249.     case QSslError::PathLengthExceeded:  
  250.         break;  
  251.     case QSslError::InvalidPurpose:  
  252.         break;  
  253.     case QSslError::CertificateUntrusted:  
  254.         break;  
  255.     case QSslError::CertificateRejected:  
  256.         break;  
  257.     case QSslError::SubjectIssuerMismatch:  
  258.         break;  
  259.     case QSslError::AuthorityIssuerSerialNumberMismatch:  
  260.         break;  
  261.     case QSslError::NoPeerCertificate:  
  262.         break;  
  263.     case QSslError::HostNameMismatch:  
  264.         break;  
  265.     case QSslError::UnspecifiedError:  
  266.         break;  
  267.     case QSslError::NoSslSupport:  
  268.         break;  
  269.     default:  
  270.         PrintMsg("no match any ssl error.");  
  271.         break;  
  272.     }  
  273. }  
  274.   
  275. void ServerThread::handleSockStateChange(const QAbstractSocket::SocketState &socketState)  
  276. {  
  277.     PrintMsg("=============Socket State==============");  
  278.     switch(socketState)  
  279.     {  
  280.     case QAbstractSocket::UnconnectedState:  
  281.         PrintMsg("The socket is not connected");  
  282.         break;  
  283.     case QAbstractSocket::HostLookupState:  
  284.         PrintMsg("The socket is performing a host name lookup");  
  285.         break;  
  286.     case QAbstractSocket::ConnectingState:  
  287.         PrintMsg("The socket has started establishing a connection");  
  288.         break;  
  289.     case QAbstractSocket::BoundState:  
  290.         PrintMsg("The socket is bound to an address and port (for servers).");  
  291.         break;  
  292.     case QAbstractSocket::ClosingState:  
  293.         PrintMsg("The socket is about to close (data may still be waiting to be written).");  
  294.         break;  
  295.     case QAbstractSocket::ListeningState:  
  296.         PrintMsg("ListeningState .For internal use only.");  
  297.         break;  
  298.     default:  
  299.         PrintMsg("Not match any states.");  
  300.         break;  
  301.     }  
  302. }  

服务器端main.cpp

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #include "include/common/net_heads.h"  
  2. #include "include/debug/debug.h"  
  3. #include "include/exception/common_exception.h"  
  4.   
  5. #include "server.h"  
  6. #include <typeinfo>  
  7. #include <QApplication>  
  8. int main(int argc , char **argv)  
  9. {  
  10.     QApplication app(argc,argv);  
  11.   
  12.     Server *server = new Server();  
  13.     server->startService();  
  14.     return app.exec();  
  15. }  



客户端(为了简化例子,有一些汲及鄙人自己的东西没有贴上来,如果真有朋友用这个例子学习的话,要自行适配):

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #ifndef NETWORKCLIENTTHREAD_H  
  2. #define NETWORKCLIENTTHREAD_H  
  3. #include "include/common/net_heads.h"  
  4. #include <QtGui/QDialog>  
  5. #include <QListWidget>  
  6. #include <QTimer>  
  7. #include <QNetworkConfigurationManager>  
  8. #include <QHostAddress>  
  9. #include <QSslSocket>  
  10. #include <QSslCipher>  
  11. #include <QSslConfiguration>  
  12. #include <QSslKey>  
  13. #include <QThread>  
  14. class NetWorkClientThread : public QThread  
  15. {  
  16.     Q_OBJECT  
  17.   
  18. public:  
  19.     NetWorkClientThread(QObject *parent = 0);  
  20.     ~NetWorkClientThread();  
  21. protected:  
  22.     void run();  
  23. public slots:  
  24.     void connectToServer();  
  25.     void discontToServer();  
  26.     void handleSocketConnected();  
  27.     void handleSocketDisconnected();  
  28.     void dataReceived();  
  29.     void sendData();  
  30.   
  31.     void handleSockStateChange(const QAbstractSocket::SocketState &socketState);  
  32.     void handleSocketError(const QAbstractSocket::SocketError &socketError);  
  33.     void handleSocketEncrypted();  
  34.     void handleSslModeChanged(QSslSocket::SslMode mode);  
  35.     void handleSslErrorList(const QList<QSslError> &errorList);  
  36.     void handlePeerVerifyError(const QSslError &error);  
  37.     void handleSslError(const QSslError &error);  
  38. private:  
  39.   
  40. private slots:  
  41.     void _run();  
  42. private:  
  43.     bool status;  
  44.     int port;  
  45.     QHostAddress *serverIP;  
  46.     QSslSocket *socket;  
  47.     QTimer *runTimer;  
  48. };  
  49. #endif // NETWORKCLIENTTHREAD_H  



[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #include "networkclientthread.h"  
  2. #include "include/debug/debug.h"  
  3. #include "getsslrelateinfo.h"  
  4. #include "crccheck.h"  
  5. #include "datatransfer.h"  
  6. #include "datatype.h"  
  7. #include <QTimer>  
  8. NetWorkClientThread::NetWorkClientThread(QObject *parent) : QThread(parent)  
  9. {  
  10.     status = false;  
  11.     port = TCP_PORT;  
  12.     serverIP = new QHostAddress();  
  13.     runTimer = new QTimer(this);  
  14.     connect(runTimer,SIGNAL(timeout()),this,SLOT(_run()));  
  15.     moveToThread(this);  
  16. }  
  17.   
  18. NetWorkClientThread::~NetWorkClientThread()  
  19. {  
  20.     delete serverIP;  
  21.     delete socket;  
  22. }  
  23.   
  24. void NetWorkClientThread::run()  
  25. {  
  26.     connectToServer();  
  27.   
  28.     runTimer->setInterval(5000);  
  29.     runTimer->setSingleShot(true);  
  30.     runTimer->start();  
  31.     exec();  
  32. }  
  33.   
  34. void NetWorkClientThread::_run()  
  35. {  
  36.     sendData();  
  37.     //QTimer::singleShot(1000,this,SLOT(discontToServer()));  
  38.     //runTimer->start();  
  39. }  
  40.   
  41. //#define SERVERNAME "winkingzhu.xicp.net"  
  42. void NetWorkClientThread::connectToServer()  
  43. {  
  44.     if(!status)  
  45.     {  
  46.         QString ip;  
  47. #ifndef SERVERNAME  
  48.         ip.append("localhost.localdomain");  
  49. #else  
  50.         ip = QString(SERVERNAME);  
  51. #endif  
  52.   
  53.         socket = new QSslSocket(this);  
  54.         if(!socket)  
  55.             PrintMsg("memory not enough");  
  56. #if 1  
  57.         /**在设置了ignoreSslErrors(...)后,sslerror 信号还是会被发射的,只是连接不会被drop掉**/  
  58.         QList<QSslError> expectedSslErrors;  
  59.         QList<QSslCertificate> certList = QSslCertificate::fromPath("../certificates/server.crt");  
  60.         QSslError error(QSslError::HostNameMismatch,certList.at(0));  
  61.         expectedSslErrors.append(error);  
  62.         socket->ignoreSslErrors(expectedSslErrors);  
  63.         GetSslRelateInfo::getCertificateDetail(certList.at(0));  
  64.   
  65. #endif  
  66. #if 0   /*查看ca证书数据库*/  
  67.         PrintMsg("=====================DEFAULT CA DATA BASE============================");  
  68.         QList<QSslCertificate > caCrtList = QSslSocket::defaultCaCertificates();  
  69.         for(int i = 0; i < caCrtList.count(); i++)  
  70.         {  
  71.             GetSslRelateInfo::getCertificateDetail(caCrtList.at(i));  
  72.         }  
  73.         PrintMsg("=====================DEFAULT CA DATA BASE END============================");  
  74. #endif  
  75.   
  76. #if 1  /*设置socket的ca数据库*/  
  77.         QList<QSslCertificate> caCertList = QSslCertificate::fromPath("../certificates/cacert.pem");  
  78.         socket->setCaCertificates(caCertList);  
  79.         caCertList = socket->caCertificates();  
  80.   
  81.         PrintMsg("=====================SOCKET CA DATA BASE============================");  
  82.         for(int i = 0; i < caCertList.count(); i++)  
  83.         {  
  84.             GetSslRelateInfo::getCertificateDetail(caCertList.at(i));  
  85.         }  
  86.         PrintMsg("=====================SOCKET CA DATA BASE END============================");  
  87. #endif  
  88.   
  89.         socket->setPrivateKey("../certificates/client.pem");  
  90.         socket->setLocalCertificate("../certificates/client.crt");  
  91.   
  92.         connect(socket,SIGNAL(encrypted()),this,SLOT(handleSocketEncrypted()));  
  93.         connect(socket,SIGNAL(modeChanged(QSslSocket::SslMode)),this,SLOT(handleSslModeChanged(QSslSocket::SslMode)));  
  94.         connect(socket,SIGNAL(sslErrors(QList<QSslError>)),this,SLOT(handleSslErrorList(QList<QSslError>)));  
  95.         connect(socket,SIGNAL(peerVerifyError(QSslError)),this,SLOT(handlePeerVerifyError(QSslError)));  
  96.         connect(socket,SIGNAL(connected()),this,SLOT(handleSocketConnected()));  
  97.         connect(socket,SIGNAL(disconnected()),this,SLOT(handleSocketDisconnected()));  
  98.         connect(socket,SIGNAL(readyRead()),this,SLOT(dataReceived()));  
  99.         connect(socket,SIGNAL(stateChanged(QAbstractSocket::SocketState)),this,SLOT(handleSockStateChange(QAbstractSocket::SocketState)));  
  100.         connect(socket,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(handleSocketError(QAbstractSocket::SocketError)));  
  101.   
  102. #ifdef SERVERNAME  
  103.         //socket->connectToHost(ip,port);  
  104.         socket->connectToHostEncrypted(ip,port);  
  105. #else  
  106.         //socket->connectToHost(*serverIP,port);  
  107.         socket->connectToHostEncrypted(ip,port);  
  108. #endif  
  109.   
  110.         PrintMsg("socket Mode: %d",socket->mode());  
  111.         status = true;  
  112.         PrintMsg("connectToServer\n");  
  113.     }  
  114.   
  115. }  
  116.   
  117. void NetWorkClientThread::discontToServer()  
  118. {  
  119.     if(socket)  
  120.         socket->disconnectFromHost();  
  121.     quit();  
  122. }  
  123.   
  124. void NetWorkClientThread::handleSocketConnected()  
  125. {  
  126.     int length = 0;  
  127.     QString msg = QString("I am in!");  
  128.     if((length = socket->write(msg.toLatin1(),msg.length())) != msg.length())  
  129.     {  
  130.         return;  
  131.     }  
  132. }  
  133.   
  134. void NetWorkClientThread::sendData()  
  135. {  
  136.     if(!socket->isEncrypted())  
  137.         return;  
  138.     QString msg = QString("hello I am client %1").arg(QThread::currentThreadId());  
  139.     socket->write(msg.toLatin1(),msg.length());  
  140. }  
  141.   
  142.   
  143. void NetWorkClientThread::handleSockStateChange(const QAbstractSocket::SocketState &socketState)  
  144. {  
  145.     PrintMsg("=============Socket State==============");  
  146.     switch(socketState)  
  147.     {  
  148.     case QAbstractSocket::UnconnectedState:  
  149.         PrintMsg("The socket is not connected");  
  150.         break;  
  151.     case QAbstractSocket::HostLookupState:  
  152.         PrintMsg("The socket is performing a host name lookup");  
  153.         break;  
  154.     case QAbstractSocket::ConnectingState:  
  155.         PrintMsg("The socket has started establishing a connection");  
  156.         break;  
  157.     case QAbstractSocket::BoundState:  
  158.         PrintMsg("The socket is bound to an address and port (for servers).");  
  159.         break;  
  160.     case QAbstractSocket::ClosingState:  
  161.         PrintMsg("The socket is about to close (data may still be waiting to be written).");  
  162.         break;  
  163.     case QAbstractSocket::ListeningState:  
  164.         PrintMsg("ListeningState .For internal use only.");  
  165.         break;  
  166.     default:  
  167.         PrintMsg("Not match any states.");  
  168.         break;  
  169.     }  
  170.     PrintMsg("===========================");  
  171. }  
  172.   
  173. void NetWorkClientThread::handleSocketEncrypted()  
  174. {  
  175.     PrintMsg("handleSocketEncrypted.");  
  176. }  
  177.   
  178. void NetWorkClientThread::handleSslModeChanged(QSslSocket::SslMode mode)  
  179. {  
  180.     PrintMsg("socket Mode Change: %d",mode);  
  181. }  
  182.   
  183. void NetWorkClientThread::handleSslErrorList(const QList<QSslError> &errorList)  
  184. {  
  185.     PrintMsg("====================Ssl Error List==================count %d",errorList.count());  
  186.     for(int i = 0 ;i < errorList.count(); i++)  
  187.     {  
  188.         QSslError SslError = errorList.at(i);  
  189.         handleSslError(SslError);  
  190.     }  
  191. }  
  192.   
  193. void NetWorkClientThread::handlePeerVerifyError(const QSslError &error)  
  194. {  
  195. #if 1  
  196.     handleSslError(error);  
  197. #endif  
  198. }  
  199.   
  200. void NetWorkClientThread::handleSslError(const QSslError &error)  
  201. {  
  202.     PrintMsg("====================Ssl Error==================");  
  203.     PrintMsg("%s",error.errorString().toAscii().data());  
  204.     QSslCertificate cer = error.certificate();  
  205.   
  206.     if(cer.isNull())  
  207.     {  
  208.         PrintMsg("Error certificate is NULL! error code: %d",error.error());  
  209.     }  
  210.     else  
  211.     {  
  212.         PrintMsg("=====Error certificate infomation========error code: %d",error.error());  
  213.         GetSslRelateInfo::getCertificateDetail(cer);  
  214.         if(cer.isValid())  
  215.         {  
  216.             PrintMsg("Certificates is Valid.");  
  217.         }  
  218.         else  
  219.         {  
  220.             PrintMsg("Certificates is Not Valid.");  
  221.         }  
  222.     }  
  223.   
  224.     switch(error.error())  
  225.     {  
  226.     case QSslError::NoError:  
  227.         break;  
  228.     case QSslError::UnableToGetIssuerCertificate:  
  229.         break;  
  230.     case QSslError::UnableToDecryptCertificateSignature:  
  231.         break;  
  232.     case QSslError::UnableToDecodeIssuerPublicKey:  
  233.         break;  
  234.     case QSslError::CertificateSignatureFailed:  
  235.         break;  
  236.     case QSslError::CertificateNotYetValid:  
  237.         break;  
  238.     case QSslError::CertificateExpired:  
  239.         break;  
  240.     case QSslError::InvalidNotBeforeField:  
  241.         break;  
  242.     case QSslError::InvalidNotAfterField:  
  243.         break;  
  244.     case QSslError::SelfSignedCertificate:  
  245.         break;  
  246.     case QSslError::SelfSignedCertificateInChain:  
  247.         break;  
  248.     case QSslError::UnableToGetLocalIssuerCertificate:  
  249.         break;  
  250.     case QSslError::UnableToVerifyFirstCertificate:  
  251.         break;  
  252.     case QSslError::CertificateRevoked:  
  253.         break;  
  254.     case QSslError::InvalidCaCertificate:  
  255.         break;  
  256.     case QSslError::PathLengthExceeded:  
  257.         break;  
  258.     case QSslError::InvalidPurpose:  
  259.         break;  
  260.     case QSslError::CertificateUntrusted:  
  261.         break;  
  262.     case QSslError::CertificateRejected:  
  263.         break;  
  264.     case QSslError::SubjectIssuerMismatch:  
  265.         break;  
  266.     case QSslError::AuthorityIssuerSerialNumberMismatch:  
  267.         break;  
  268.     case QSslError::NoPeerCertificate:  
  269.         break;  
  270.     case QSslError::HostNameMismatch:  
  271.         if(cer.subjectInfo(QSslCertificate::CommonName) == QString("GameServer"))  
  272.         {  
  273.             //socket->ignoreSslErrors();  
  274.         }  
  275.         //socket->ignoreSslErrors();  
  276.         break;  
  277.     case QSslError::UnspecifiedError:  
  278.         break;  
  279.     case QSslError::NoSslSupport:  
  280.         break;  
  281.     default:  
  282.         PrintMsg("no match any ssl error.");  
  283.         break;  
  284.     }  
  285. }  
  286.   
  287. void NetWorkClientThread::handleSocketError(const QAbstractSocket::SocketError &socketError)  
  288. {  
  289.     PrintMsg("================socket error=================");  
  290.     switch(socketError)  
  291.     {  
  292.     case QAbstractSocket::ConnectionRefusedError:  
  293.         PrintMsg("The connection was refused by the peer (or timed out).");  
  294.         break;  
  295.     case QAbstractSocket::RemoteHostClosedError:  
  296.         PrintMsg("The remote host closed the connection. Note that the client socket (i.e., this socket) will be closed after the remote close notification has been sent.");  
  297.         break;  
  298.     case QAbstractSocket::HostNotFoundError:  
  299.         PrintMsg("The host address was not found.");  
  300.         break;  
  301.     case QAbstractSocket::SocketAccessError:  
  302.         PrintMsg("The socket operation failed because the application lacked the required privileges.");  
  303.         break;  
  304.     case QAbstractSocket::SocketResourceError:  
  305.         PrintMsg("The local system ran out of resources (e.g., too many sockets).");  
  306.         break;  
  307.     case QAbstractSocket::SocketTimeoutError:  
  308.         PrintMsg("The socket operation timed out.");  
  309.         break;  
  310.     case QAbstractSocket::DatagramTooLargeError:  
  311.         PrintMsg("The datagram was larger than the operating system's limit (which can be as low as 8192 bytes).");  
  312.         break;  
  313.     case QAbstractSocket::NetworkError:  
  314.         PrintMsg("An error occurred with the network (e.g., the network cable was accidentally plugged out).");  
  315.         break;  
  316.     case QAbstractSocket::AddressInUseError:  
  317.         PrintMsg("The address specified to bind() is already in use and was set to be exclusive.");  
  318.         break;  
  319.     case QAbstractSocket::SocketAddressNotAvailableError:  
  320.         PrintMsg("The address specified to bind() does not belong to the host.");  
  321.         break;  
  322.     case QAbstractSocket::UnsupportedSocketOperationError:  
  323.         PrintMsg("The requested socket operation is not supported by the local operating system (e.g., lack of IPv6 support).");  
  324.         break;  
  325.     case QAbstractSocket::ProxyAuthenticationRequiredError:  
  326.         PrintMsg("The socket is using a proxy, and the proxy requires authentication.");  
  327.         break;  
  328.     case QAbstractSocket::SslHandshakeFailedError:  
  329.         PrintMsg("The SSL/TLS handshake failed, so the connection was closed (only used in SslSocket)");  
  330.         break;  
  331.     case QAbstractSocket::UnfinishedSocketOperationError:  
  332.         PrintMsg("Used by AbstractSocketEngine only, The last operation attempted has not finished yet (still in progress in the background).");  
  333.         break;  
  334.     case QAbstractSocket::ProxyConnectionRefusedError:  
  335.         PrintMsg("Could not contact the proxy server because the connection to that server was denied");  
  336.         break;  
  337.     case QAbstractSocket::ProxyConnectionClosedError:  
  338.         PrintMsg("The connection to the proxy server was closed unexpectedly (before the connection to the final peer was established)");  
  339.         break;  
  340.     case QAbstractSocket::ProxyConnectionTimeoutError:  
  341.         PrintMsg("The connection to the proxy server timed out or the proxy server stopped responding in the authentication phase.");  
  342.         break;  
  343.     case QAbstractSocket::ProxyNotFoundError:  
  344.         PrintMsg("The proxy address set with setProxy() (or the application proxy) was not found.");  
  345.         break;  
  346.     case QAbstractSocket::ProxyProtocolError:  
  347.         PrintMsg("The connection negotiation with the proxy server because the response from the proxy server could not be understood.");  
  348.         break;  
  349.     case QAbstractSocket::UnknownSocketError:  
  350.         PrintMsg("An unidentified error occurred.");  
  351.         break;  
  352.     default:  
  353.         PrintMsg("Not match any errors.");  
  354.         break;  
  355.     }  
  356. }  
  357.   
  358.   
  359. void NetWorkClientThread::handleSocketDisconnected()  
  360. {  
  361.     PrintMsg("disconnect");  
  362. }  
  363.   
  364. void NetWorkClientThread::dataReceived()  
  365. {  
  366.     while(socket->bytesAvailable() > 0 )  
  367.     {  
  368.         QByteArray datagram;  
  369.         datagram.resize(socket->bytesAvailable());  
  370.         socket->read(datagram.data(),datagram.size());  
  371.         qDebug() << datagram;  
  372.     }  
  373. }  


include/debug/debug.h

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #ifndef __DEBUG_H  
  2. #define __DEBUG_H  
  3. /*这个头文件按下面的需要,包含必要的头文件,比如QString*/  
  4. #include "globalinclude.h"  
  5. #define DEBUG_PROG  
  6.   
  7. #ifdef _WIN32  
  8. /************Windows*****************/  
  9. /*获取当前文件,当函数,当前行作为QString*/  
  10. #define POS_INF QString("File: %1 Func: %2 Line %3").arg(__FILE__).arg(__FUNCTION__).arg(__LINE__)  
  11.   
  12. #ifdef DEBUG_PROG  
  13. #define PrintMsg(str,...) (qDebug("File: %s Func: %s Line: %d "str,__FILE__,__FUNCTION__,__LINE__,__VA_ARGS__))  
  14. #else  
  15. #define PrintMsg(str,...)  
  16. #endif //DEBUG_PROG  
  17. /************************************/  
  18. #else  
  19. /*************Linux*******************/  
  20. /*获取当前文件,当函数,当前行作为QString*/  
  21. #define POS_INF QString("File: %1 Func: %2 Line %3").arg(__FILE__).arg(__func__).arg(__LINE__)  
  22.   
  23. #ifdef DEBUG_PROG  
  24. //#define PrintMsg(str,arg...) (printf("File: %s Func: %s Line: %d "str,__FILE__,__func__,__LINE__,##arg))  
  25. #define PrintMsg(str,arg...) (qDebug("File: %s Func: %s Line: %d "str,__FILE__,__func__,__LINE__,##arg))  
  26. #else  
  27. #define PrintMsg(str,arg...)  
  28. #endif //DEBUG_PROG  
  29. /**************************************/  
  30. #endif //_WIN32  
  31.    
  32.   
  33. #endif //__DEBUG_  


客户端main.cpp

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #include "include/common/connect_retry.h"  
  2. #include "include/debug/debug.h"  
  3. #include "include/exception/common_exception.h"  
  4. #include <QApplication>  
  5. #include "networkclientthread.h"  
  6. #include <QList>  
  7. int main(int argc , char **argv)  
  8. {  
  9.     QApplication app(argc,argv);  
  10.   
  11.     QList <NetWorkClientThread *> list;  
  12.     NetWorkClientThread *networkThread;  
  13.     do  
  14.     {  
  15.         for(int i = 0; i < 1; i++)  
  16.         {  
  17.             networkThread = new NetWorkClientThread;  
  18.             list.append(networkThread);  
  19.             networkThread->start();  
  20.         }  
  21.         for(int i = 0; i < list.count(); i++)  
  22.         {  
  23.             list.at(i)->wait();  
  24.         }  
  25.         for(int i = 0; i < list.count(); i++)  
  26.         {  
  27.             delete list.at(i);  
  28.         }  
  29.         list.clear();  
  30.     }  
  31.     while(0);  
  32.     return app.exec();  
  33. }  



===============我是分割线,分割,分割=====================

以上例子证书生成过程(生成是在RHEL6.2上生成的):

.鄙人的CA配置文件:/etc/pki/tls/openssl.cnf

####################################################################


#

# OpenSSL exampleconfiguration file.

# This is mostly beingused for generation of certificate requests.

#

# This definition stopsthe following lines choking if HOME isn't

# defined.

HOME = .

RANDFILE =$ENV::HOME/.rnd

# Extra OBJECTIDENTIFIER info:

#oid_file =$ENV::HOME/.oid

oid_section = new_oids

# To use thisconfiguration file with the "-extfile" option of the

# "openssl x509"utility, name here the section containing the

# X.509v3 extensions touse:

# extensions =

# (Alternatively, use aconfiguration file that has only

# X.509v3 extensions inits main [= default] section.)

[ new_oids ]

# We can add new OIDsin here for use by 'ca', 'req' and 'ts'.

# Add a simple OID likethis:

# testoid1=1.2.3.4

# Or use config filesubstitution like this:

#testoid2=${testoid1}.5.6

# Policies used by theTSA examples.

tsa_policy1 = 1.2.3.4.1

tsa_policy2 =1.2.3.4.5.6

tsa_policy3 =1.2.3.4.5.7

####################################################################

[ ca ]

default_ca = CA_default# The default ca section

####################################################################

[ CA_default ]

dir = /etc/pki/CA #Where everything is kept

certs = $dir/certs #Where the issued certs are kept

crl_dir = $dir/crl #Where the issued crl are kept

database =$dir/index.txt # database index file.

#unique_subject = no #Set to 'no' to allow creation of

# several ctificateswith same subject.

new_certs_dir =$dir/newcerts # default place for new certs.

certificate =$dir/cacert.pem # The CA certificate

serial = $dir/serial #The current serial number

crlnumber =$dir/crlnumber # the current crl number

# must be commented outto leave a V1 CRL

crl = $dir/crl.pem #The current CRL

private_key =$dir/private/cakey.pem# The private key

RANDFILE =$dir/private/.rand # private random number file

x509_extensions =usr_cert # The extentions to add to the cert

# Comment out thefollowing two lines for the "traditional"

# (and highly broken)format.

name_opt = ca_default #Subject Name options

cert_opt = ca_default #Certificate field options

# Extension copyingoption: use with caution.

# copy_extensions =copy

# Extensions to add toa CRL. Note: Netscape communicator chokes on V2 CRLs

# so this is commentedout by default to leave a V1 CRL.

# crlnumber must alsobe commented out to leave a V1 CRL.

# crl_extensions =crl_ext

default_days = 365 #how long to certify for修改这个值,可改变默认给签多少天(也可以在签证时,指出有效时长)

default_crl_days= 30 #how long before next CRL

default_md = default #use public key default MD

preserve = no # keeppassed DN ordering

# A few difference wayof specifying how similar the request should look

# For type CA, thelisted attributes must be the same, and the optional

# and supplied fieldsare just that :-)

policy = policy_match

# For the CA policy

[ policy_match ]

countryName = match

stateOrProvinceName =match

organizationName =match

organizationalUnitName= optional

commonName = supplied

emailAddress = optional

# For the 'anything'policy

# At this point intime, you must list all acceptable 'object'

# types.

[ policy_anything ]

countryName = optional

stateOrProvinceName =optional

localityName = optional

organizationName =optional

organizationalUnitName= optional

commonName = supplied

emailAddress = optional

####################################################################

[ req ]

default_bits = 2048

default_md = sha1

default_keyfile =privkey.pem

distinguished_name =req_distinguished_name

attributes =req_attributes

x509_extensions = v3_ca# The extentions to add to the self signed cert

# Passwords for privatekeys if not present they will be prompted for

# input_password =secret

# output_password =secret

# This sets a mask forpermitted string types. There are several options.

# default:PrintableString, T61String, BMPString.

# pkix :PrintableString, BMPString (PKIX recommendation before 2004)

# utf8only: onlyUTF8Strings (PKIX recommendation after 2004).

# nombstr :PrintableString, T61String (no BMPStrings or UTF8Strings).

# MASK:XXXX a literalmask value.

# WARNING: ancientversions of Netscape crash on BMPStrings or UTF8Strings.

string_mask = utf8only

# req_extensions =v3_req # The extensions to add to a certificate request

[req_distinguished_name ]

countryName = CountryName (2 letter code)

countryName_default =CN

countryName_min = 2

countryName_max = 2

stateOrProvinceName =State or Province Name (full name)

#stateOrProvinceName_default= GuangDong

localityName = LocalityName (eg, city)

localityName_default =GuangZhou

0.organizationName =Organization Name (eg, company)

0.organizationName_default= XXX, Inc.

# we can do this but itis not needed normally :-)

#1.organizationName =Second Organization Name (eg, company)

#1.organizationName_default= World Wide Web Pty Ltd

organizationalUnitName= Organizational Unit Name (eg, section)

#organizationalUnitName_default=

commonName = CommonName (eg, your name or your server\'s hostname)

commonName_max = 64

emailAddress = EmailAddress

emailAddress_max = 64

# SET-ex3 = SETextension number 3

[ req_attributes ]

challengePassword = Achallenge password

challengePassword_min =4

challengePassword_max =20

unstructuredName = Anoptional company name

[ usr_cert ]

# These extensions areadded when 'ca' signs a request.

# This goes againstPKIX guidelines but some CAs do it and some software

# requires this toavoid interpreting an end user certificate as a CA.

basicConstraints=CA:FALSE

# Here are someexamples of the usage of nsCertType. If it is omitted

# the certificate canbe used for anything *except* object signing.

# This is OK for an SSLserver.

# nsCertType = server

# For an object signingcertificate this would be used.

# nsCertType = objsign

# For normal client usethis is typical

# nsCertType = client,email

# and for everythingincluding object signing:

# nsCertType = client,email, objsign

# This is typical inkeyUsage for a client certificate.

# keyUsage =nonRepudiation, digitalSignature, keyEncipherment

# This will bedisplayed in Netscape's comment listbox.

nsComment = "OpenSSLGenerated Certificate"

# PKIX recommendationsharmless if included in all certificates.

subjectKeyIdentifier=hash

authorityKeyIdentifier=keyid,issuer

# This stuff is forsubjectAltName and issuerAltname.

# Import the emailaddress.

#subjectAltName=email:copy

# An alternative toproduce certificates that aren't

# deprecated accordingto PKIX.

#subjectAltName=email:move

# Copy subject details

#issuerAltName=issuer:copy

#nsCaRevocationUrl =http://www.domain.dom/ca-crl.pem

#nsBaseUrl

#nsRevocationUrl

#nsRenewalUrl

#nsCaPolicyUrl

#nsSslServerName

# This is required forTSA certificates.

# extendedKeyUsage =critical,timeStamping

[ v3_req ]

# Extensions to add toa certificate request

basicConstraints =CA:FALSE

keyUsage =nonRepudiation, digitalSignature, keyEncipherment

[ v3_ca ]


# Extensions for atypical CA


# PKIX recommendation.

subjectKeyIdentifier=hash

authorityKeyIdentifier=keyid:always,issuer

# This is what PKIXrecommends but some broken software chokes on critical

# extensions.

#basicConstraints =critical,CA:true

# So we do thisinstead.

basicConstraints =CA:true

# Key usage: this istypical for a CA certificate. However since it will

# prevent it being usedas an test self-signed certificate it is best

# left out by default.

# keyUsage = cRLSign,keyCertSign

# Some might want thisalso

# nsCertType = sslCA,emailCA

# Include email addressin subject alt name: another PKIX recommendation

#subjectAltName=email:copy

# Copy issuer details

#issuerAltName=issuer:copy

# DER hex encoding ofan extension: beware experts only!

# obj=DER:02:03

# Where 'obj' is astandard or added object

# You can even overridea supported extension:

# basicConstraints=critical, DER:30:03:01:01:FF

[ crl_ext ]

# CRL extensions.

# Only issuerAltNameand authorityKeyIdentifier make any sense in a CRL.

#issuerAltName=issuer:copy

authorityKeyIdentifier=keyid:always

[ proxy_cert_ext ]

# These extensionsshould be added when creating a proxy certificate

# This goes againstPKIX guidelines but some CAs do it and some software

# requires this toavoid interpreting an end user certificate as a CA.

basicConstraints=CA:FALSE

# Here are someexamples of the usage of nsCertType. If it is omitted

# the certificate canbe used for anything *except* object signing.

# This is OK for an SSLserver.

# nsCertType = server

# For an object signingcertificate this would be used.

# nsCertType = objsign

# For normal client usethis is typical

# nsCertType = client,email

# and for everythingincluding object signing:

# nsCertType = client,email, objsign

# This is typical inkeyUsage for a client certificate.

# keyUsage =nonRepudiation, digitalSignature, keyEncipherment

# This will bedisplayed in Netscape's comment listbox.

nsComment = "OpenSSLGenerated Certificate"

# PKIX recommendationsharmless if included in all certificates.

subjectKeyIdentifier=hash

authorityKeyIdentifier=keyid,issuer

# This stuff is forsubjectAltName and issuerAltname.

# Import the emailaddress.

#subjectAltName=email:copy

# An alternative toproduce certificates that aren't

# deprecated accordingto PKIX.

#subjectAltName=email:move

# Copy subject details

#issuerAltName=issuer:copy

#nsCaRevocationUrl =http://www.domain.dom/ca-crl.pem

#nsBaseUrl

#nsRevocationUrl

#nsRenewalUrl

#nsCaPolicyUrl

#nsSslServerName

# This really needs tobe in place for it to be a proxy certificate.

proxyCertInfo=critical,language:id-ppl-anyLanguage,pathlen:3,policy:foo

####################################################################

[ tsa ]

default_tsa =tsa_config1 # the default TSA section

[ tsa_config1 ]

# These are used by theTSA reply generation only.

dir = ./demoCA # TSAroot directory

serial = $dir/tsaserial# The current serial number (mandatory)

crypto_device = builtin# OpenSSL engine to use for signing

signer_cert =$dir/tsacert.pem # The TSA signing certificate

# (optional)

certs = $dir/cacert.pem# Certificate chain to include in reply

# (optional)

signer_key =$dir/private/tsakey.pem # The TSA private key (optional)

default_policy =tsa_policy1 # Policy if request did not specify it

# (optional)

other_policies =tsa_policy2, tsa_policy3 # acceptable policies (optional)

digests = md5, sha1 #Acceptable message digests (mandatory)

accuracy = secs:1,millisecs:500, microsecs:100 # (optional)

clock_precision_digits= 0 # number of digits after dot. (optional)

ordering = yes # Isordering defined for timestamps?

# (optional, default:no)

tsa_name = yes # Mustthe TSA name be included in the reply?

# (optional, default:no)

ess_cert_id_chain = no# Must the ESS cert id chain be included?

# (optional, default:no)

####################################################################



.创建必须目录

[root@Winking-PC CA]#pwd

/etc/pki/CA

[root@Winking-PC CA]#mkdir {certs,newcerts,crl}

[root@Winking-PC CA]#ls

certs crl newcertsprivate /*如果没有这几个文件,可以自己创建*/

[root@Winking-PC CA]#echo 00 > serial; /*生成一个初始序列号*/

[root@Winking-PC CA]#touch index.txt /*创建index.txt文件*/

[root@Winking-PC CA]#echo 00 > crlnumber /*创建吊销证书号码文件*/

[root@Winking-PC CA]#ls

certs crl crlnumberindex.txt newcerts private serial

.CA中心生成自己的私钥

[root@Winking-PC CA]#openssl genrsa -out private/cakey.pem -des3 2048

Generating RSA privatekey, 2048 bit long modulus

.............................................................................+++

....................................................................+++

e is 65537 (0x10001)

Enter pass phrase forprivate/cakey.pem: /*输入使用这个私钥时所要输入的密码"你的密码"*/

Verifying - Enter passphrase for private/cakey.pem:

[root@Winking-PC CA]#ls private/

cakey.pem



.通过CA私钥生成CA根证书

[root@Winking-PC CA]#openssl req -new -x509 -key private/cakey.pem -days 14600 >cacert.pem

Enter pass phrase forprivate/cakey.pem:

You are about to beasked to enter information that will be incorporated

into your certificaterequest.

What you are about toenter is what is called a Distinguished Name or a DN.

There are quite a fewfields but you can leave some blank

For some fields therewill be a default value,

If you enter '.', thefield will be left blank.

-----

Country Name (2 lettercode) [CN]:CN

State or Province Name(full name) []:GuangDong

Locality Name (eg,city) [GuangZhou]:

Organization Name (eg,company) [XXX, Inc.]:

Organizational UnitName (eg, section) []:

Common Name (eg, yourname or your server's hostname) []:HOSTNAME

Email Address []:

[root@Winking-PC CA]#ls

cacert.pem certs crlcrlnumber index.txt newcerts private serial



.生成需要申请证书的用户私钥

/*这里在用户文件夹里,生成用户私钥时,也可以指定密码以提高安全性,就像生成CA私钥的步骤一样*/

[Winking@Winking-PCcertificates]$ openssl genrsa 1024 > server.pem

Generating RSA privatekey, 1024 bit long modulus

.......++++++

.....++++++

e is 65537 (0x10001)

[Winking@Winking-PCcertificates]$ ls

server.pem



.使用用户私钥生成一个证书请求文件

[Winking@Winking-PCcertificates]$ openssl req -new -key server.pem -out server.csr

You are about to beasked to enter information that will be incorporated

into your certificaterequest.

What you are about toenter is what is called a Distinguished Name or a DN.

There are quite a fewfields but you can leave some blank

For some fields therewill be a default value,

If you enter '.', thefield will be left blank.

-----

Country Name (2 lettercode) [CN]:CN

State or Province Name(full name) []:GuangDong

Locality Name (eg,city) [GuangZhou]:GuangZhou

Organization Name (eg,company) [XXX, Inc.]:XXX, Inc.

Organizational UnitName (eg, section) []: /*以上填写均要跟CA中心的一致*/

Common Name (eg, yourname or your server's hostname) []:USERHOSTNAME

Email Address []:

Please enter thefollowing 'extra' attributes

to be sent with yourcertificate request

A challenge password[]:

An optional companyname []:

[Winking@Winking-PCcertificates]$ ls

server.csr server.pem

.CA中心签名

由于是在本机操作,所以现在直接在本文件夹操作CA中心签名的步骤.

[Winking@Winking-PCcertificates]$ sudo openssl ca -in server.csr -days 12775 -outserver.crt /*12775= 35*/

Using configurationfrom /etc/pki/tls/openssl.cnf

Enter pass phrase for/etc/pki/CA/private/cakey.pem:    <<在这里输入创建CA私钥的那个密码

Check that the requestmatches the signature

Signature ok

Certificate Details:

Serial Number: 0 (0x0)

Validity

Not Before: Jan 806:11:04 2014 GMT

Not After : Dec 3006:11:04 2048 GMT

Subject:

countryName = CN

stateOrProvinceName =GuangDong

organizationName =XXX, Inc.

commonName = HOSTNAME

X509v3 extensions:

X509v3 BasicConstraints:

CA:FALSE

Netscape Comment:

OpenSSL GeneratedCertificate

X509v3 Subject KeyIdentifier:

1F:B2:9A:2F:AD:52:38:C7:BB:F1:09:37:BB:6F:F9:1B:A2:3C:08:06

X509v3 Authority KeyIdentifier:

keyid:42:02:2E:FA:BB:4C:FF:41:8B:15:05:EE:B2:51:C8:96:C2:4B:39:91

Certificate is to becertified until Dec 30 06:11:04 2048 GMT (12775 days)

Sign the certificate?[y/n]:y


1 out of 1 certificaterequests certified, commit? [y/n]y

Write out database with1 new entries

Data Base Updated

[Winking@Winking-PCcertificates]$ ls

server.crt server.csrserver.pem

.吊销用户证书

1.生成吊销证书

[root@Winking-PCnewcerts]# pwd

/etc/pki/CA/newcerts

[root@Winking-PCnewcerts]# ls

00.pem

[root@Winking-PCnewcerts]# openssl ca -revoke 00.pem

Using configurationfrom /etc/pki/tls/openssl.cnf

Enter pass phrase for/etc/pki/CA/private/cakey.pem:

Revoking Certificate00.

Data Base Updated

[root@Winking-PCnewcerts]# ls

00.pem

2.生成过期列表

[root@Winking-PC CA]#openssl ca -gencrl -out /etc/pki/CA/crl/crl.pem

Using configurationfrom /etc/pki/tls/openssl.cnf

Enter pass phrase for/etc/pki/CA/private/cakey.pem:

[root@Winking-PC CA]#ls crl/

crl.pem

然后crl.pem被连接服务器的客户端导入到过期列表就行了



参考:

http://dgraves.org/content/qt-notes-working-qsslsocket

http://doc.qt.digia.com/solutions/4/qtsslsocket/sslguide.html

.....

还参考了挺多国内前辈的博客,忘记了...,非常感谢大笑

版权声明:本文为博主原创文章,未经博主允许不得转载。

0 0
原创粉丝点击