Skip to content

Instantly share code, notes, and snippets.

@eahydra
Created September 19, 2012 05:03
Show Gist options
  • Save eahydra/3747774 to your computer and use it in GitHub Desktop.
Save eahydra/3747774 to your computer and use it in GitHub Desktop.
pe file checksum
unsigned short ChkSum(unsigned int CheckSum, void *FileBase, int Length)
{
int *Data;
int sum;
if ( Length && FileBase != NULL)
{
Data = (int *)FileBase;
do
{
sum = *(unsigned short *)Data + CheckSum;
Data = (int *)((char *)Data + 2);
CheckSum = (unsigned short)sum + (sum >> 16);
}
while ( --Length );
}
return CheckSum + (CheckSum >> 16);
}
unsigned int PECheckSum(void *FileBase, unsigned int FileSize)
{
void *RemainData;
int RemainDataSize;
unsigned int PeHeaderSize;
unsigned int HeaderCheckSum;
unsigned int PeHeaderCheckSum;
unsigned int FileCheckSum;
PIMAGE_NT_HEADERS NtHeaders;
NtHeaders = ImageNtHeader(FileBase);
if ( NtHeaders )
{
HeaderCheckSum = NtHeaders->OptionalHeader.CheckSum;
PeHeaderSize = (unsigned int)NtHeaders - (unsigned int)FileBase +
((unsigned int)&NtHeaders->OptionalHeader.CheckSum - (unsigned int)NtHeaders);
RemainDataSize = (FileSize - PeHeaderSize - 4) >> 1;
RemainData = &NtHeaders->OptionalHeader.Subsystem;
PeHeaderCheckSum = ChkSum(0, FileBase, PeHeaderSize >> 1);
FileCheckSum = ChkSum(PeHeaderCheckSum,RemainData, RemainDataSize);
if ( FileSize & 1 )
{
FileCheckSum += (unsigned short)*((char *)FileBase + FileSize - 1);
}
}
else
{
FileCheckSum = 0;
}
return (FileSize + FileCheckSum);
}
void TestPEFile(void)
{
TCHAR *FileName = _T("C:\\windows\\system32\\drivers\\wimmount.sys");
HANDLE FileHandle = CreateFile(FileName,
GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
0,
NULL);
if (FileHandle != INVALID_HANDLE_VALUE)
{
HANDLE FileMapHandle = CreateFileMapping(FileHandle,
NULL,
PAGE_READONLY,
0,0,NULL);
if (FileMapHandle != NULL)
{
unsigned short *FileBase = (unsigned short *)MapViewOfFile(FileMapHandle,FILE_MAP_READ,0,0,0);
if (FileBase != NULL)
{
DWORD FileSize = GetFileSize(FileHandle,NULL);
DWORD HeaderCheckSum = 0;
DWORD CheckSum = 0;
MapFileAndCheckSum(FileName,&HeaderCheckSum,&CheckSum);
DWORD sum = PECheckSum(FileBase,FileSize);
if (sum == HeaderCheckSum)
{
printf("Valid Pe File\n");
}
else
{
printf("Invalid Pe File\n");
}
UnmapViewOfFile(FileBase);
}
CloseHandle(FileMapHandle);
}
CloseHandle(FileHandle);
}
return;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment