PE操作类--判断PE文件

判断一个文件是否为合法PE文件通常只需判断“MZ”头和“PE”头

//判断是否为PE结构
BOOL CPe32 ::IsPeFile(TCHAR* pFileName)
{
             if (pFileName == NULL)
            {
                         return FALSE ;
            }
             //获得指定文件句柄
             HANDLE hFile = CreateFile (pFileName, GENERIC_READ , FILE_SHARE_READ , NULL,
                         OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL , 0);
             if (hFile == NULL || hFile == INVALID_HANDLE_VALUE)
            {          
                         return FALSE ;
            }
             WORD dwTempRead; //word 占两个字节,就是头两个字节,两字节的缓冲区
             DWORD dwReadInFactSize; //读取字节数=2
             //读取文件开始两字节,即MZ头
             BOOL bRead = ReadFile(hFile, &dwTempRead, sizeof( WORD), &dwReadInFactSize, NULL);
             if (!bRead || sizeof (WORD) != dwReadInFactSize)
            {
                        CloseHandle(hFile);
                         return FALSE ;
            }
             if (dwTempRead != 0x5a4d)
            {
                        CloseHandle(hFile);
                         return FALSE ;
            }

             //得到e_lfanew 成员在IMAGE_DOS_HEADER 结构中的偏移
             // e_lfanew is File address of new exe header
             DWORD dwSize = offsetof (IMAGE_DOS_HEADER, e_lfanew);

             //将文件指针移动到得到e_lfanew成员
            SetFilePointer(hFile, dwSize, NULL, FILE_BEGIN );

             //读取得到e_lfanew成员的内容,也就是PE头在文件中的偏移
            bRead = ReadFile(hFile, &dwTempRead, sizeof(WORD ), &dwReadInFactSize, NULL);
             if (!bRead || sizeof (WORD) != dwReadInFactSize)
            {
                        CloseHandle(hFile);
                         return FALSE ;
            }
             //将指针移动到PE头
            SetFilePointer(hFile, dwTempRead, NULL, FILE_BEGIN );

             //读取PE标志,NtHeader是定义的一个结构体对象
             IMAGE_NT_HEADERS NtHeader = {0};
             //把整个PE头结构读取
            bRead = ReadFile(hFile, &NtHeader, sizeof(NtHeader), &dwReadInFactSize, NULL);
             if (!bRead || sizeof (NtHeader) != dwReadInFactSize)
            {
                        CloseHandle(hFile);
                         return FALSE ;
            }
             if (NtHeader.Signature != 0x4550)
            {
                        CloseHandle(hFile);
                         return FALSE ;
            }
            CloseHandle(hFile);
             //该文件属于PE格式,返回TRUE.
             return TRUE ;
}

 

你可能感兴趣的:(安全,PE)