⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 serverdlg.cpp

📁 实现通信过程中的数据加密(AES, DES, SHA-256,SHA-384,SHA512, RSA)。 测试加解密效率等
💻 CPP
字号:
// ServerDlg.cpp : implementation file
//

#include "SockWork.h"
#include "Server.h"
#include "ServerDlg.h"
#include "afxmt.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
CSockWork sw;
CCrypt    crypt;
UINT      total;
UINT      normal;
UINT      bad;
UINT      recvSize;
UINT      hlen;
UINT      rsa_length;
UINT      decrypt_type;

DWORD     start_time;
DWORD     end_time;
DWORD     decryptTime;

DWORD     decrypt_key_start;
DWORD     decrypt_key_end;
DWORD     decrypt_key_time;

DWORD     decrypt_message_start;
DWORD     decrypt_message_end;
DWORD     decrypt_message_time;

BOOL      out;
BOOL      flag;
BOOL      decrypt;
HWND      hwnd;
HANDLE    hProcessIO[MAX_NUM_CPU];
HANDLE    hMain;
CMutex    mutex;
DWORD WINAPI  ThreadProc(LPVOID lpParam);
DWORD WINAPI  MainProc(LPVOID lpParam);

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CServerDlg dialog

CServerDlg::CServerDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CServerDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CServerDlg)
	//m_nPort = 0;
	m_strSeed = _T("");
	m_strInfo = _T("");
	m_nTotal  = 0;
	m_nNormal = 0;
	m_nBad    = 0;
	m_strTime = _T("");
	m_strDTime = _T("");
	m_nHash = 0;
	m_nRsaKeyLength = 0;
	m_nDecryptType = 0;
	m_nDecrypt = 0;
	m_strDecryptKeyTime = _T("");
	m_strDecryptMessageTime = _T("");
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CServerDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CServerDlg)
	//DDX_Text(pDX, IDC_EDIT2, m_nPort);
	DDX_Text(pDX, IDC_EDIT3, m_strSeed);
	DDX_Text(pDX, IDC_EDIT4, m_strInfo);
	DDX_Text(pDX, IDC_EDIT1, m_nTotal);
	DDX_Text(pDX, IDC_EDIT5, m_nNormal);
	DDX_Text(pDX, IDC_EDIT6, m_nBad);
	DDX_Text(pDX, IDC_EDIT7, m_strTime);
	DDX_Text(pDX, IDC_EDIT2, m_strDTime);
	DDX_Radio(pDX, IDC_RADIO10, m_nHash);
	DDX_Radio(pDX, IDC_RADIO15, m_nRsaKeyLength);
	DDX_Radio(pDX, IDC_RADIO5, m_nDecryptType);
	DDX_Radio(pDX, IDC_RADIO1, m_nDecrypt);
	DDX_Text(pDX, IDC_EDIT8, m_strDecryptKeyTime);
    DDX_Text(pDX, IDC_EDIT9, m_strDecryptMessageTime);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CServerDlg, CDialog)
	//{{AFX_MSG_MAP(CServerDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_MESSAGE(WM_END,OnEnd)
	ON_BN_CLICKED(IDC_BUTTON4, OnButton4)
	ON_BN_CLICKED(IDC_BUTTON1, OnButton1)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CServerDlg message handlers

BOOL CServerDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here
	sw.InitSock();
	m_strInfo = "1. 生成的密钥文件在程序\r\n   同一目录下。\r\n2. pub.txt为公钥。\r\n3. pri.txt为私钥。";
	//m_nPort   = 1234;
	UpdateData(FALSE);
	
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CServerDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CServerDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CServerDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CServerDlg::OnButton4() 
{
	// TODO: Add your control notification handler code here
	UpdateData();

	
	if(m_nRsaKeyLength == 0) rsa_length = 512;
	else if(m_nRsaKeyLength == 1) rsa_length = 1024;
	else rsa_length = 2048;

	CCrypt crypt;
	crypt.setRsaPriFilename("pri.txt");
	crypt.setRsaPubFilename("pub.txt");
	crypt.setRsaKeyLength(rsa_length);
	crypt.setCreateKeySeed(m_strSeed.GetBuffer(0));
	if(crypt.rsaCreateKey() == 0)
		AfxMessageBox("密钥生成成功!");
	else 
		AfxMessageBox("密钥生成失败!");
}

HANDLE CompletionPort;
SOCKET sListen;

LONG CServerDlg::OnEnd()
{
	SYSTEM_INFO SystemInfo;
	GetSystemInfo(&SystemInfo);

	if(hMain != NULL)
		TerminateThread(hMain,0);
	
	DWORD dwByteTrans = 0;
	PostQueuedCompletionStatus(CompletionPort, dwByteTrans, 0, 0);
	CloseHandle(CompletionPort);
	
	for(int i = 0; i < SystemInfo.dwNumberOfProcessors  ; i++)
	{
		if(hProcessIO[i] != NULL)
			TerminateThread(hProcessIO[i],0);			
	}

	m_nTotal = total;
	m_nNormal= normal;
	m_nBad   = bad;
	m_strTime.Format("%d ms",end_time - start_time - decryptTime);
	m_strDTime.Format("%d ms", decryptTime);
	m_strDecryptKeyTime.Format("%d ms",decrypt_key_time);
	m_strDecryptMessageTime.Format("%d ms",decrypt_message_time);
	UpdateData(FALSE);

	closesocket(sListen);

	this->GetDlgItem(IDC_BUTTON1)->EnableWindow(TRUE);
	return 0;
}

void CServerDlg::OnButton1() 
{
	// TODO: Add your control notification handler code here
	UpdateData();
	this->GetDlgItem(IDC_BUTTON1)->EnableWindow(FALSE); 
	total = 0;
	normal= 0;
	bad   = 0;
	out   = false;
	flag  = false;
	decryptTime = 0;
	decrypt_key_time = 0;
	decrypt_message_time = 0;
	decrypt_type = m_nDecryptType;
	decrypt = m_nDecrypt;

	if(m_nHash == 0) hlen = 16;
	else if(m_nHash == 1) hlen = 32;
	else if(m_nHash == 2) hlen = 64;
	else hlen = 48;

	hwnd  = GetSafeHwnd();

	crypt.setRsaPriFilename("pri.txt");
	crypt.setRsaDecryptor();
	
	CompletionPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0);
	// 根据系统的CPU来创建工作者线程
	hMain = CreateThread(NULL, 0, MainProc, NULL, 0, NULL);

	SYSTEM_INFO SystemInfo;
	GetSystemInfo(&SystemInfo);
	
	for(int i = 0; i < SystemInfo.dwNumberOfProcessors ; i++)
	{
		hProcessIO[i] = CreateThread(NULL, 0, ThreadProc, CompletionPort, 0, NULL);
		if(hProcessIO[i] == NULL)
			AfxMessageBox("线程创建失败!");
			
	}
}

DWORD WINAPI  MainProc(LPVOID lpParam)
{
	sListen = sw.BindServer(SERV_PORT);
	if(sListen == NULL)
	{
		AfxMessageBox("监听失败!");
		::PostMessage(hwnd, WM_END, 0, 0);
		return 0;
	}
	//Sleep(1000);
	SOCKET sClient;
	LPPER_HANDLE_DATA PerHandleData;
    LPPER_IO_OPERATION_DATA PerIoData;

	while(!out)
	{
		//sClient = WSAAccept(sListen, NULL, NULL, NULL, 0);
		sClient = accept(sListen, 0, 0);

		PerHandleData = new PER_HANDLE_DATA();
	    PerIoData = new PRE_IO_OPERATION_DATA();
		
		PerHandleData->socket = sClient;
		
		CreateIoCompletionPort((HANDLE)sClient, CompletionPort, (DWORD)PerHandleData, 0);
		
		memset(PerIoData,0, sizeof(PRE_IO_OPERATION_DATA));
		PerIoData->databuf.buf = PerIoData->buffer;
		PerIoData->databuf.len = 6;
		
		DWORD Flags = 0;
		DWORD dwRecv = 0;
		WSARecv(sClient, &PerIoData->databuf, 1, &dwRecv, &Flags, &PerIoData->overlapped, NULL);
	}
	
	return 0;
}

DWORD WINAPI ThreadProc(LPVOID lpParam)
{
	HANDLE CompletionPort = (HANDLE)lpParam;
	DWORD  BytesReceived;
	DWORD  flags;
	DWORD  dwRecv;
	DWORD  st;
    DWORD  et;
	LPPER_HANDLE_DATA PerHandleData;
	LPPER_IO_OPERATION_DATA PerIoOperationData;
	MESSAGE msg;
	string message;
	UINT   len;
	UINT   last = 0;
	byte   m[65];
	string key;
	
	while(!out)
	{
		if(0 == GetQueuedCompletionStatus(CompletionPort, &BytesReceived, (LPDWORD)&PerHandleData, (LPOVERLAPPED *)&PerIoOperationData, INFINITE))
		{
			if(GetLastError() == WAIT_TIMEOUT || GetLastError() == ERROR_NETNAME_DELETED)
			{
				closesocket(PerHandleData->socket);
				delete PerHandleData;
				delete PerIoOperationData;
				continue;
			}
			return 0;
		}
		
		if(BytesReceived == 0)    //客户端已断开
		{
			closesocket(PerHandleData->socket);
			delete PerHandleData;
			delete PerIoOperationData;
			continue;
		}
		msg.ciper_text = PerIoOperationData->buffer;
		
		if(strcmp(msg.ciper_text, "begin") == 0 || strcmp(msg.ciper_text, "end") == 0)  //标记测试的开始与结束
		{
			CSingleLock lock(&mutex);
			lock.Lock();
			if(strcmp(msg.ciper_text, "begin") == 0)
				start_time = GetTickCount();
			else if(strcmp(msg.ciper_text, "end") == 0)
			{
				end_time   = GetTickCount();
				out = true;
				::PostMessage(hwnd, WM_END, 0, 0);
			}
			lock.Unlock();
		}
		
		else if(!flag)  
		{
			CSingleLock lock(&mutex);
			lock.Lock();
			memcpy(&recvSize,PerIoOperationData->buffer, sizeof(UINT));
			flag = true;
			lock.Unlock();
		}
		
		else//解密数据, 并判断收到的数据是否被篡改过
		{
			if(decrypt == 0)
			{
				try
				{
					len = strlen(msg.ciper_text);
					msg.des_key = PerIoOperationData->buffer + len +1;
					memcpy(msg.sha, (byte *)PerIoOperationData->buffer + len + strlen(msg.des_key) + 2, hlen);
					total++;
					
					if(strcmp(msg.ciper_text, "") != 0)
					{
						st = GetTickCount();
						decrypt_key_start = st;
						key = crypt.rsaDecrypt(msg.des_key);
						decrypt_key_end = GetTickCount();
						decrypt_key_time += decrypt_key_end - decrypt_key_start;
						
						decrypt_message_start = decrypt_key_end;
						if(decrypt_type == 0)
						{
							crypt.setDesKey(key);
							message = crypt.desDecrypt(msg.ciper_text);
						}
						else 
						{
							crypt.setAesKey(key);
							message = crypt.aesDecrypt(msg.ciper_text);
						}
						decrypt_message_end = GetTickCount();
						decrypt_message_time += decrypt_message_end - decrypt_message_start;
						
						if(hlen == 16)
							crypt.shaEncrypt((char *)message.c_str(),m);
						else if(hlen == 32)
							crypt.sha256Encrypt((char *)message.c_str(),m);
						else if(hlen == 64)
							crypt.sha512Encrypt((char *)message.c_str(),m);
						else crypt.sha384Encrypt((char *)message.c_str(),m);
						m[hlen] = '\0';
						et = GetTickCount();
						CSingleLock lock(&mutex);
						lock.Lock();
						normal++;		
						decryptTime += et - st;
						lock.Unlock();
					}
				}
				catch(...)
				{
					AfxMessageBox("参数设置不正确!");
					::PostMessage(hwnd, WM_END, 0, 0);
					return 0;
				}
			}
			else
			{ 
				if(strcmp(msg.ciper_text, "") != 0)
					total++;
				//do nothing!
			}
		}
		flags = 0;
		dwRecv = 0;
		memset(PerIoOperationData, 0, sizeof(PRE_IO_OPERATION_DATA));
		PerIoOperationData->databuf.buf = PerIoOperationData->buffer;
		if(flag)
			PerIoOperationData->databuf.len = recvSize;
		else
			PerIoOperationData->databuf.len = sizeof(UINT);
		WSARecv(PerHandleData->socket, &PerIoOperationData->databuf, 1, &dwRecv, &flags, &PerIoOperationData->overlapped, NULL);		
	}
	return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -