判断是不是一个PE文件有很多种方法,我们用的方法是:
先读取Dos头,判断e_magic是否等于"MZ",然后再读取PE文件头的头字节,判断是不是 "PE00"。这样就能确定是不是一个有效的PE文件。代码如下:
//选择文件
void CPEDlg :: OnButton1()
{
// TODO: Add your control notification handler code here
TCHAR tzFilter [] = _T( "可执行文件(*.exe)|*.exe|所有文件(*.*)|*.*||");
CFileDialog dlgFile( TRUE , NULL , NULL , OFN_HIDEREADONLY , tzFilter , this);
if ( IDOK == dlgFile . DoModal())
{
m_strFilePath = dlgFile . GetPathName();
UpdateData( FALSE);
}
}
//判断是否是PE文件
void CPEDlg :: OnButton2()
{
// TODO: Add your control notification handler code here
HANDLE hFile = INVALID_HANDLE_VALUE; //打开的PE文件句柄
IMAGE_DOS_HEADER DosHeader = { 0 };
DWORD dwReadLen = 0;
DWORD dwNTSignature = 0;
//创建文件
hFile = CreateFile( m_strFilePath , GENERIC_READ , FILE_SHARE_READ , NULL , OPEN_EXISTING , FILE_ATTRIBUTE_NORMAL , NULL);
if ( hFile == INVALID_HANDLE_VALUE)
{
MessageBox( "打开文件失败");
return;
}
//读取文件
if ( ! ReadFile( hFile , & DosHeader , sizeof( DosHeader ), & dwReadLen , NULL))
{
CloseHandle( hFile);
MessageBox( "读取文件失败");
return;
}
//判断DOS头部是否为MZ
if ( DosHeader . e_magic != IMAGE_DOS_SIGNATURE)
{
CloseHandle( hFile);
MessageBox( "不是PE文件");
return;
}
SetFilePointer( hFile , DosHeader . e_lfanew , NULL , FILE_BEGIN);
//读取PE的NT头字节
ReadFile( hFile , & dwNTSignature , sizeof( dwNTSignature ), & dwReadLen , NULL);
//判断PE标志
if ( dwNTSignature != IMAGE_NT_SIGNATURE)
{
MessageBox( "不是PE文件");
CloseHandle( hFile);
return;
}
CloseHandle( hFile);
hFile = INVALID_HANDLE_VALUE;
MessageBox( "是PE文件");
}
void CPEDlg :: OnButton1()
{
// TODO: Add your control notification handler code here
TCHAR tzFilter [] = _T( "可执行文件(*.exe)|*.exe|所有文件(*.*)|*.*||");
CFileDialog dlgFile( TRUE , NULL , NULL , OFN_HIDEREADONLY , tzFilter , this);
if ( IDOK == dlgFile . DoModal())
{
m_strFilePath = dlgFile . GetPathName();
UpdateData( FALSE);
}
}
//判断是否是PE文件
void CPEDlg :: OnButton2()
{
// TODO: Add your control notification handler code here
HANDLE hFile = INVALID_HANDLE_VALUE; //打开的PE文件句柄
IMAGE_DOS_HEADER DosHeader = { 0 };
DWORD dwReadLen = 0;
DWORD dwNTSignature = 0;
//创建文件
hFile = CreateFile( m_strFilePath , GENERIC_READ , FILE_SHARE_READ , NULL , OPEN_EXISTING , FILE_ATTRIBUTE_NORMAL , NULL);
if ( hFile == INVALID_HANDLE_VALUE)
{
MessageBox( "打开文件失败");
return;
}
//读取文件
if ( ! ReadFile( hFile , & DosHeader , sizeof( DosHeader ), & dwReadLen , NULL))
{
CloseHandle( hFile);
MessageBox( "读取文件失败");
return;
}
//判断DOS头部是否为MZ
if ( DosHeader . e_magic != IMAGE_DOS_SIGNATURE)
{
CloseHandle( hFile);
MessageBox( "不是PE文件");
return;
}
SetFilePointer( hFile , DosHeader . e_lfanew , NULL , FILE_BEGIN);
//读取PE的NT头字节
ReadFile( hFile , & dwNTSignature , sizeof( dwNTSignature ), & dwReadLen , NULL);
//判断PE标志
if ( dwNTSignature != IMAGE_NT_SIGNATURE)
{
MessageBox( "不是PE文件");
CloseHandle( hFile);
return;
}
CloseHandle( hFile);
hFile = INVALID_HANDLE_VALUE;
MessageBox( "是PE文件");
}