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

📄 testendedlg.cpp

📁 一个aes的加密解密的简单的演示工程
💻 CPP
字号:
// TestEnDeDlg.cpp : implementation file
//

#include "stdafx.h"
#include "TestEnDe.h"
#include "TestEnDeDlg.h"

#include <shlwapi.h>
#include <string>
#include <memory>
#include <exception>
#include <malloc.h>

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

CString SSOEncrypt(CString pchInData);
CString SSODecrypt(CString pchInData);

//__stdcall  
BYTE*	m_pFileData;
UINT	m_nStrLength;
DWORD	m_dwS[2 * R + 4];
int		m_nKey;
int		m_blockSize = 16;

CString g_oStrError = _T("ERROR");
CString g_oStrSuccess = _T("SUCCESS");
CRijndael oRijndael;

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

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()

/////////////////////////////////////////////////////////////////////////////
// CTestEnDeDlg dialog

CTestEnDeDlg::CTestEnDeDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CTestEnDeDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CTestEnDeDlg)
	//m_Src = _T("");
	//m_Target = _T("");
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CTestEnDeDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CTestEnDeDlg)
	//DDX_Text(pDX, IDC_EDITSRC, m_Src);
	//DDX_Text(pDX, IDC_EDITTARGET, m_Target);
	DDX_Control(pDX, IDC_RICHEDITSRC, m_RichSrc);
	DDX_Control(pDX, IDC_RICHEDITTARGET, m_RichTarget);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CTestEnDeDlg, CDialog)
	//{{AFX_MSG_MAP(CTestEnDeDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(ID_Decrypt, OnDecrypt)
	ON_BN_CLICKED(ID_Encrypt, OnEncrypt)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CTestEnDeDlg message handlers

BOOL CTestEnDeDlg::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
	
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CTestEnDeDlg::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 CTestEnDeDlg::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 CTestEnDeDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

//Error Beep Signal
void ErrorBeep()
{
	//MessageBeep(MB_OK); //asynchronous
	MessageBeep(0xFFFFFFFF); //asynchronous
}

//Optimized Function to convert an unsigned char to a Hex string of length 2
void Char2Hex(unsigned char ch, char* szHex)
{
	static unsigned char saucHex[] = "0123456789ABCDEF";
	szHex[0] = saucHex[ch >> 4];
	szHex[1] = saucHex[ch&0xF];
	szHex[2] = 0;
}

//Function to convert a Hex string of length 2 to an unsigned char
bool Hex2Char(char const* szHex, unsigned char& rch)
{
	if(*szHex >= '0' && *szHex <= '9')
		rch = *szHex - '0';
	else if(*szHex >= 'A' && *szHex <= 'F')
		rch = *szHex - 55; //-'A' + 10
	else
		//Is not really a Hex string
		return false; 
	szHex++;
	if(*szHex >= '0' && *szHex <= '9')
		(rch <<= 4) += *szHex - '0';
	else if(*szHex >= 'A' && *szHex <= 'F')
		(rch <<= 4) += *szHex - 55; //-'A' + 10;
	else
		//Is not really a Hex string
		return false;
	return true;
}

//Function to convert binary string to hex string
void Binary2Hex(unsigned char const* pucBinStr, int iBinSize, char* pszHexStr)
{
	int i;
	char szHex[3];
	unsigned char const* pucBinStr1 = pucBinStr;
	*pszHexStr = 0;
	for(i=0; i<iBinSize; i++,pucBinStr1++)
	{
		Char2Hex(*pucBinStr1, szHex);
		strcat(pszHexStr, szHex);
	}
}

//Function to convert hex string to binary string
bool Hex2Binary(char const* pszHexStr, unsigned char* pucBinStr, int iBinSize)
{
	int i;
	unsigned char ch;
	for(i=0; i<iBinSize; i++,pszHexStr+=2,pucBinStr++)
	{
		if(false == Hex2Char(pszHexStr, ch))
			return false;
		*pucBinStr = ch;
	}
	return true;
}

void AESParams(CString& roStrKeyData,int& riKeyLength, int& riBlockSize, int& riMode, int& riPadding)
{
	roStrKeyData = "abcdefghabcdefgh";
	
	//Key Length
	riKeyLength = 16;

	//Block Size
	riBlockSize = 16;

	//Mode
	riMode = 0;

	//Padding
	riPadding = 0;
}

int Pad(char* in, int iLength)
{
	int iRes = iLength%m_blockSize;
	if(iRes != 0)
	{
		//Is the caller's responsability to ensure that in buffer is large enough
		int iPadded = m_blockSize - iRes;
		char* pin = in+iLength;
		for(int i=0; i<iPadded; i++, pin++)
			*pin = 0;
		
		return iLength + iPadded;
	}
	return iLength;
}

CString SSOEncrypt(CString oStrInput)
{
	CString strOutPut;
	CString oStrKeyData;
	char acKey[32];
	int iMode, iPadding;
	int iLength,iKeyLength, iBlockSize;
	AESParams(oStrKeyData, iKeyLength, iBlockSize, iMode, iPadding);
	iLength = oStrInput.GetLength();
	//iLength /= 2;
	if(iLength > 32)
		iLength = 32;
	Hex2Binary(LPCTSTR(oStrKeyData), reinterpret_cast<unsigned char*>(acKey), iLength);
	oRijndael.Initialize(acKey, 32, CRijndael::sm_chain0, iKeyLength, iBlockSize,iMode, iPadding);

	try
	{
		char* pcIn;
		char* pcOut;
		char* pcHex;
		int iLen, iLen1;
		
		iLen = oStrInput.GetLength();

		//Estimate Padding
		int iBlockSize = 16;
		if(iBlockSize > -1)
		{
			if(iLen%iBlockSize != 0)
				iLen1 = (iLen/iBlockSize+1)*iBlockSize;
			else
				iLen1 = iLen;
		}
		else
			iLen1 = iLen;
		pcIn = static_cast<char*>(_alloca(iLen1));
		pcOut = static_cast<char*>(_alloca(iLen1));
		strcpy(pcIn, LPCTSTR(oStrInput));
		memcpy(oRijndael.m_chain, oRijndael.m_chain0, m_blockSize);
		if(iBlockSize > -1)
			Pad(pcIn, iLen);
		oRijndael.Encrypt(pcIn, pcOut, iLen1);
		iLen = (iLen1<<1)+1;
		pcHex = static_cast<char*>(_alloca(iLen));
		Binary2Hex(reinterpret_cast<unsigned char*>(pcOut), iLen1, pcHex);
		//pcHex[iLen] = 0;

		strOutPut.Format("%s",pcHex);
		return strOutPut;
	}
	catch(exception const& roException)
	{
		MessageBox(NULL,CString(roException.what()), g_oStrError, MB_OK|MB_ICONINFORMATION);
		ErrorBeep();
	}
	return "";
}

CString SSODecrypt(CString oStrInput)
{
	CString oStrKeyData;

	CString strOutPut;
	char acKey[32];
	int iMode, iPadding;
	int iLength,iKeyLength, iBlockSize;
	AESParams(oStrKeyData, iKeyLength, iBlockSize, iMode, iPadding);

	iLength = oStrInput.GetLength();
	iLength /= 2;
	if(iLength > 32)
		iLength = 32;
	Hex2Binary(LPCTSTR(oStrKeyData), reinterpret_cast<unsigned char*>(acKey), iLength);
	oRijndael.Initialize(acKey, 32, CRijndael::sm_chain0, iKeyLength, iBlockSize,iMode, iPadding);

	try
	{
		char* pcIn;
		char* pcOut;
		
		int iLen = oStrInput.GetLength()/2;
		pcIn = static_cast<char*>(_alloca(iLen));
		Hex2Binary(LPCTSTR(oStrInput), reinterpret_cast<unsigned char*>(pcIn), iLen);
		pcOut = static_cast<char*>(_alloca(iLen+1));
		memcpy(oRijndael.m_chain, oRijndael.m_chain0, m_blockSize);//poMethod->ResetChain();
		oRijndael.Decrypt(pcIn, pcOut, iLen);//CRijndael::Decrypt
		strOutPut.Format("%s",pcOut);
		return strOutPut;
	}
	catch(exception const& roException)
	{
		MessageBox(NULL,CString(roException.what()), g_oStrError, MB_OK|MB_ICONINFORMATION);
		ErrorBeep();
		
	}

	return "";
}

DWORD __stdcall InCallback(DWORD dwCookie, LPBYTE pbBuff, LONG cb, LONG *pcb)
{
	CString *psBuffer = (CString *)dwCookie;

	if (cb > psBuffer->GetLength()) cb = psBuffer->GetLength();

	for (int i=0;i<cb;i++) {
		*(pbBuff+i) = psBuffer->GetAt(i);
	}

	*pcb = cb;

	*psBuffer = psBuffer->Mid(cb);

	return 0;
}

DWORD __stdcall OutCallback(DWORD dwCookie, LPBYTE pbBuff, LONG cb, LONG *pcb)
{
	CString sThisWrite;
	sThisWrite.GetBufferSetLength(cb);

	CString *psBuffer = (CString *)dwCookie;
	
	for (int i=0;i<cb;i++) {
		sThisWrite.SetAt(i,*(pbBuff+i));
	}

	*psBuffer += sThisWrite;

	*pcb = sThisWrite.GetLength();
	sThisWrite.ReleaseBuffer();
	return 0;
}

void CTestEnDeDlg::OnCancel() 
{
	// TODO: Add extra cleanup here
	
	CDialog::OnCancel();
}

void CTestEnDeDlg::OnDecrypt() 
{
	UpdateData(true);
	CRichEditCtrl* m_RichSrc = (CRichEditCtrl*)this->GetDlgItem(IDC_RICHEDITSRC);
	CRichEditCtrl* m_RichTarget = (CRichEditCtrl*)this->GetDlgItem(IDC_RICHEDITTARGET);
	EDITSTREAM es;
	CString strSrc;
	es.dwCookie = (DWORD)&strSrc; // Pass a pointer to the CString to the callback function 
	es.pfnCallback = OutCallback;
	m_RichSrc->StreamOut(SF_TEXT,es);

	strSrc.TrimRight();
	CString strTarget = SSODecrypt(strSrc);
	es.dwCookie = (DWORD)&strTarget; // Pass a pointer to the CString to the callback function
	es.pfnCallback = InCallback; // Specify the pointer to the callback function
	m_RichTarget->StreamIn(SF_TEXT,es);
	UpdateData(false);
}

void CTestEnDeDlg::OnEncrypt() 
{
	UpdateData(true);
	CRichEditCtrl* m_RichSrc = (CRichEditCtrl*)this->GetDlgItem(IDC_RICHEDITSRC);
	CRichEditCtrl* m_RichTarget = (CRichEditCtrl*)this->GetDlgItem(IDC_RICHEDITTARGET);
	EDITSTREAM es;
	CString strSrc;
	es.dwCookie = (DWORD)&strSrc; // Pass a pointer to the CString to the callback function 
	es.pfnCallback = OutCallback;
	m_RichSrc->StreamOut(SF_TEXT,es);
	
	CString strTarget = SSOEncrypt(strSrc);
	es.dwCookie = (DWORD)&strTarget; // Pass a pointer to the CString to the callback function
	es.pfnCallback = InCallback; // Specify the pointer to the callback function
	m_RichTarget->StreamIn(SF_TEXT,es);
	UpdateData(false);
}

BOOL CTestEnDeDlg::PreCreateWindow(CREATESTRUCT& cs) 
{
	// TODO: Add your specialized code here and/or call the base class
	AfxInitRichEdit();
	return CDialog::PreCreateWindow(cs);
}

⌨️ 快捷键说明

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