* I have two buttons in a MFC dialog box to test the AES encryption and
cannot figure out what is wrong. *
*Button 1:*
*Not all encryptions are not correct.*
*Button 2:*
*All encryptions are correct. There is an error message after everything is
done.*
HEAP[TestCryptApp.exe]: Invalid address specified to RtlValidateHeap(
00800000, 00AF17D8 )
TestCryptApp.exe has triggered a breakpoint.
--
--
You received this message because you are subscribed to the "Crypto++ Users"
Google Group.
To unsubscribe, send an email to [email protected].
More information about Crypto++ and this group is available at
http://www.cryptopp.com.
---
You received this message because you are subscribed to the Google Groups
"Crypto++ Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.
// TestCryptAppDlg.cpp : implementation file
//
#include "stdafx.h"
#include "TestCryptApp.h"
#include "TestCryptAppDlg.h"
#include "afxdialogex.h"
#include <string>
#include <random>
#include <iostream>
#include <fstream>
#include "BasicCryptoPPWrap.h"
#include <string>
#include <sstream>
#include <stdio.h>
using namespace CryptoPP;
using namespace std;
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialogEx
{
public:
CAboutDlg();
// Dialog Data
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()
// CTestCryptAppDlg dialog
CTestCryptAppDlg::CTestCryptAppDlg(CWnd* pParent /*=NULL*/)
: CDialogEx(CTestCryptAppDlg::IDD, pParent)
, m_KeyLength(128)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
static const char alphabet[] =
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"0123456789";
static const size_t N_STRS = 1000;
static const size_t S_LEN = 32;
std::random_device rd;
std::default_random_engine rng(rd());
std::uniform_int_distribution<> dist(0, sizeof(alphabet) / sizeof(*alphabet) - 2);
firstName.reserve(N_STRS);
std::generate_n(std::back_inserter(firstName), firstName.capacity(),
[&] { std::string str;
str.reserve(S_LEN);
std::generate_n(std::back_inserter(str), S_LEN,
[&]() { return alphabet[dist(rng)]; });
return str; });
std::copy(firstName.begin(), firstName.end(), std::ostream_iterator<std::string>(std::cout, "\n"));
}
void CTestCryptAppDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_EDIT1, m_key);
DDX_Control(pDX, IDC_EDIT2, m_iv);
DDX_Control(pDX, IDC_EDIT5, m_text);
DDX_Control(pDX, IDC_EDIT3, m_encrypted);
DDX_Control(pDX, IDC_EDIT4, m_decrypted);
}
BEGIN_MESSAGE_MAP(CTestCryptAppDlg, CDialogEx)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_BUTTON1, &CTestCryptAppDlg::OnBnClickedButton1)
ON_BN_CLICKED(IDC_BUTTON2, &CTestCryptAppDlg::OnBnClickedButton2)
END_MESSAGE_MAP()
// CTestCryptAppDlg message handlers
BOOL CTestCryptAppDlg::OnInitDialog()
{
CDialogEx::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)
{
BOOL bNameValid;
CString strAboutMenu;
bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
ASSERT(bNameValid);
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 CTestCryptAppDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialogEx::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 CTestCryptAppDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<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
{
CDialogEx::OnPaint();
}
}
// The system calls this function to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CTestCryptAppDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
// Convert from ascii hex representation to binary
// Examples;
// "00" -> 0
// "2a" -> 42
// "ff" -> 255
// Case insensitive, 2 characters of input required, no error checking
int Hex2Bin( const TCHAR *s )
{
int ret=0;
int i;
for( i=0; i<2; i++ )
{
TCHAR c = *s++;
int n=0;
if( '0'<=c && c<='9' )
n = c-'0';
else if( 'a'<=c && c<='f' )
n = 10 + c-'a';
else if( 'A'<=c && c<='F' )
n = 10 + c-'A';
ret = n + ret*16;
}
return ret;
}
//Function to convert hex string to binary string
bool Hex2Block(const CString& HexStr, TCHAR * pucBinStr)
{
TCHAR sour[3] ;
for(int ii=0; ii < HexStr.GetLength()/2;ii++)
{
sour[0] = (TCHAR)HexStr[2*ii];
sour[1] = (TCHAR)HexStr[2*ii+1];
sour[2] = 0;
pucBinStr[ii] = Hex2Bin(sour);
}
return true;
}
CString Block2Hex(const unsigned char *dataBlock,unsigned int blockLength)
{
CString strResult = "", strTmp;
for(unsigned int i=0;i<blockLength;i++)
{
strTmp.Format("%02X",dataBlock[i]);
strResult+=strTmp;
}
strResult+"\0";
return strResult;
}
//bLOCK
byte CTestCryptAppDlg::iv[] = {0xb1, 0x59, 0x12, 0xe, 0xcd, 0xbd, 0x4d, 0x8e
, 0x9d, 0xed, 0xe9, 0xda, 0xd4, 0x9, 0x29, 0xcc};
// Key length 128, 192, 256
byte CTestCryptAppDlg::key128[] = {0x21, 0x23, 0x24, 0x61, 0x35, 0x34, 0x3f, 0x33,
0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef};
byte CTestCryptAppDlg::key192[] = {0x21, 0x23, 0x24, 0x61, 0x35, 0x34, 0x3f, 0x33,
0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef,
0x84, 0x63, 0x59, 0xd4, 0xcb, 0xc4, 0x97, 0xf9};
byte CTestCryptAppDlg::key256[] = {0x21, 0x23, 0x24, 0x61, 0x35, 0x34, 0x3f, 0x33,
0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef,
0x84, 0x63, 0x59, 0xd4, 0xcb, 0xc4, 0x97, 0xf9,
0x96, 0xc2, 0xb3, 0x7e, 0xb0, 0xe6, 0x73, 0x52
};
CString CTestCryptAppDlg::EncryptAESString(const CString& strInput)
{
CString str= _T("");
string plaintext;
byte cipherText[256],plain[32];
memset(cipherText,0,256);
memset(plain,' ',32);
int messageLen = 16;
plaintext = strInput;
memcpy(plain,strInput,32);
for(int i=strInput.GetLength(); i<32;i++)
{
plain[i]=' ';
}
switch( m_KeyLength)
{
case 128:
{
CFB_Mode<AES>::Encryption cfbEncryption(key128, sizeof(key128), iv);
cfbEncryption.ProcessData( (byte*)cipherText, (byte*)plaintext.c_str(),messageLen);
}
break;
case 192:
{
messageLen = 24;
CFB_Mode<AES>::Encryption cfbEncryption(key192, sizeof(key192), iv);
cfbEncryption.ProcessData( (byte*)cipherText, (byte*)plaintext.c_str(),messageLen);
}
break;
case 256:
{
messageLen = 32;
CFB_Mode<AES>::Encryption cfbEncryption(key256, sizeof(key256), iv);
cfbEncryption.ProcessData( (byte*)cipherText, plain,messageLen);
}
break;
}
// TRACE("Key Size = %d\n",m_KeyLength);
// TRACE("Original Text =%s\n",strInput);
int size = strlen((const char*)cipherText);
TRACE("Cipher text binary\n");
for (int i=0;i<size;i++)
{
TRACE("%c",cipherText[i]);
}
TRACE("\n");
str = Block2Hex( cipherText, size);
TRACE("Cipher Text1 =%s\n",str);
// str = toString(cipherText,size).c_str();
// TRACE("Cipher Text2 =%s\n",str);
return str;
}
CString CTestCryptAppDlg::EncryptAESStrings(const CString& strInput)
{
int bsize = 16;
switch( m_KeyLength)
{
case 128:
{
bsize = 16;
}
break;
case 192:
{
bsize = 24;
}
break;
case 256:
{
bsize = 32;
}
break;
}
CString str= _T(""), str1;
int nLength = (int)(strInput.GetLength()/bsize)+1;
if( (nLength-1)*bsize == strInput.GetLength())
{
nLength = nLength-1;
}
for (int i=0;i<nLength ;i++)
{
str1 =strInput.Mid(i*bsize,min(bsize,strInput.GetLength()-i*bsize));
CString strCipher = EncryptAESString(str1);
// TRACE("strCipher=\n",strCipher);
// str+=strCipher.Mid(0,min(32,strCipher.GetLength()));
str+=strCipher.Mid(0,bsize*2);
}
return str;
}
CString CTestCryptAppDlg::DecryptAESString(const CString& strInput)
{
CString str= _T("");
byte decipherText[32], cipherText[256];
memset(decipherText,0,32);
memset(cipherText,0,256);
int messageLen = 16;
if(strInput.GetLength() < 1) return _T("");
Hex2Block(strInput, (TCHAR*)cipherText);
/*
_TUCHAR buffer[100];
sprintf_s(buffer,"%s",strInput);
buffer[strInput.GetLength()]='\0';
strtohex(buffer,cipherText,strInput.GetLength());
*/
// TRACE("Cipher binary Text =%s\n",cipherText);
switch(m_KeyLength)
{
case 128:
{
CFB_Mode<AES>::Decryption cfbDecryption128(key128, sizeof(key128), iv);
cfbDecryption128.ProcessData((byte*)decipherText,(byte*)cipherText, messageLen);
}
break;
case 192:
{
messageLen = 24;
CFB_Mode<AES>::Decryption cfbDecryption192(key192, sizeof(key192), iv);
cfbDecryption192.ProcessData((byte*)decipherText,(byte*)cipherText, messageLen);
}
break;
case 256:
{
messageLen = 32;
CFB_Mode<AES>::Decryption cfbDecryption256(key256, sizeof(key256), iv);
cfbDecryption256.ProcessData((byte*)decipherText,(byte*)cipherText, messageLen);
}
break;
}
str = decipherText;
// TRACE("Cipher Text1 =%s\n",cipherText);
// TRACE("Decipher Text =%s\n",str);
return str;
}
CString CTestCryptAppDlg::DecryptAESStrings(const CString& strInput)
{
int bsize = 32;
switch( m_KeyLength)
{
case 128:
{
bsize = 32;
}
break;
case 192:
{
bsize = 48;
}
break;
case 256:
{
bsize = 64;
}
break;
}
CString str(""),str1("");
int nLength = (int)(strInput.GetLength()/bsize)+1;
if( (nLength-1)*bsize == strInput.GetLength()) nLength = nLength-1;
for (int i=0;i<nLength ;i++)
{
str1 =strInput.Mid(i*bsize,min(bsize,strInput.GetLength()-i*bsize));
CString strDecipher =DecryptAESString(str1);
str += strDecipher.Mid(0,min(bsize/2,strDecipher.GetLength()));
}
return str;
}
void CTestCryptAppDlg::OnBnClickedButton1()
{
// TODO: Add your control notification handler code here
m_KeyLength = 256;
string plain,cipher,encoded, recovered;
for (int i=0;i<(int)firstName.size(); i++)
{
plain = firstName[i];
cipher = EncryptAESStrings(plain.c_str());
recovered = DecryptAESStrings(cipher.c_str()).TrimRight();
TRACE("Plain Text =%s\n",plain.c_str());
TRACE("cipher Text =%s\n",cipher.c_str());
if(plain != recovered)
TRACE("Recovered is different from plain\n");
TRACE("recovered Text =%s\n\n",recovered.c_str());
}
}
void CTestCryptAppDlg::Encryptions4(string &plain,string &cipher,string &encoded)
{
try
{
cipher.clear();
encoded.clear();
TRACE("plain text: %s\n", plain.c_str());
CryptoPP::StreamTransformationFilter stfEncryptor(*m_cbcEncryption, new CryptoPP::StringSink(cipher));
stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plain.c_str() ), plain.length() + 1 );
stfEncryptor.MessageEnd();
StringSource(cipher, true,
new HexEncoder(
new StringSink(encoded)
) // HexEncoder
); // StringSource
}
catch(const CryptoPP::Exception& e)
{
TRACE("e.what() text: %s\n", e.what());
return;
}
TRACE("cipher text: : %s\n", encoded.c_str() );
}
void CTestCryptAppDlg::Decryptions4(string &encoded,string &recovered)
{
string cipher;
try
{
recovered.clear();
char *name2;
name2 = (char*) malloc(encoded.length() + 1); // don't forget to free!!!!
strcpy_s(name2, encoded.length() + 1,encoded.c_str());
const char* hex_str = name2;
std::string result_string ;
unsigned int ch ;
for( ; std::sscanf( hex_str, "%2x", &ch ) == 1 ; hex_str += 2 )
result_string += ch ;
free(name2);
CryptoPP::StreamTransformationFilter stfDecryptor(*m_cbcDecryption, new CryptoPP::StringSink( recovered ) );
stfDecryptor.Put( reinterpret_cast<const unsigned char*>( result_string.c_str() ), result_string.size() );
stfDecryptor.MessageEnd();
TRACE("recovered text: : %s\n", recovered.c_str() );
}
catch(const CryptoPP::Exception& e)
{
cerr << e.what() << endl;
return;
}
}
void CTestCryptAppDlg::OnBnClickedButton2()
{
string plain, cipher, encoded, recovered;
m_aesEncryption = new CryptoPP::AES::Encryption((byte *)key256, sizeof(key256));
m_aesDecryption = new CryptoPP::AES::Decryption((byte *)key256, sizeof(key256));
m_cbcEncryption = new CryptoPP::CBC_Mode_ExternalCipher::Encryption(*m_aesEncryption, (byte *)iv );
m_cbcDecryption = new CryptoPP::CBC_Mode_ExternalCipher::Decryption(*m_aesDecryption, (byte *)iv );
for (int i=0;i< (int)firstName.size(); i++)
{
plain = firstName[i];
Encryptions4(plain,cipher,encoded);
Decryptions4(encoded, recovered);
plain.clear(),cipher.clear(),encoded.clear(), recovered.clear();
}
delete m_cbcEncryption;
delete m_cbcDecryption;
delete m_aesEncryption;
delete m_aesDecryption;
}
// TestCryptAppDlg.h : header file
//
#pragma once
#include "afxwin.h"
#include "..\dll.h"
#include <string>
#include <vector>
// CTestCryptAppDlg dialog
class CTestCryptAppDlg : public CDialogEx
{
// Construction
public:
CTestCryptAppDlg(CWnd* pParent = NULL); // standard constructor
// Dialog Data
enum { IDD = IDD_TESTCRYPTAPP_DIALOG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
HICON m_hIcon;
// Generated message map functions
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
DECLARE_MESSAGE_MAP()
void Encryptions4(std::string &plain,std::string &cipher,std::string &encoded);
void Decryptions4(std::string &encoded,std::string &recovered);
CryptoPP::AES::Encryption* m_aesEncryption;
CryptoPP::CBC_Mode_ExternalCipher::Encryption *m_cbcEncryption;
CryptoPP::AES::Decryption* m_aesDecryption;
CryptoPP::CBC_Mode_ExternalCipher::Decryption *m_cbcDecryption;
static byte iv[16], key128[16], key192[24], key256[32];
public:
CEdit m_key;
CEdit m_iv;
CEdit m_text;
CEdit m_encrypted;
CEdit m_decrypted;
afx_msg void OnBnClickedButton1();
afx_msg void OnBnClickedButton2();
CString EncryptAESString(const CString& strInput);
CString DecryptAESString(const CString& strInput);
CString EncryptAESStrings(const CString& strInput);
CString DecryptAESStrings(const CString& strInput);
int m_KeyLength;
std::vector<std::string> firstName,lastName;
};