#include <windows.h>
#include <imagehlp.h>
#include <stdio.h>
void CalcChecksum( char *szPeFile );
__inline void PrintUsage( void );
int main(int argc, char* argv[])
{
if( argc != 2 )
{
PrintUsage();
return 0;
}
CalcChecksum(argv[1]);
return 0;
}
/*++
Routine Description:
Calculates a new checksum for the PE image by calling imagehlp.dll
Arguments:
szPeFile - PE file name
Return Value:
void
--*/
void
CalcChecksum(
char *szPeFile
)
{
DWORD dwHeaderSum = 0;
DWORD dwCheckSum = 0;
HANDLE hFile;
DWORD cb;
IMAGE_DOS_HEADER dosHdr;
IMAGE_NT_HEADERS ntHdr;
//
// Open the file and calculate the CheckSum
//
if( MapFileAndCheckSum(szPeFile, &dwHeaderSum, &dwCheckSum) != CHECKSUM_SUCCESS )
{
printf("Failed to open specified PE file!/n");
return;
}
hFile = CreateFile( szPeFile,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
0,
NULL
);
if( hFile == INVALID_HANDLE_VALUE )
{
printf("Failed to open specified PE file!/n");
return;
}
//
// Seek to the beginning of the file
//
SetFilePointer( hFile, 0, 0, FILE_BEGIN );
//
// Read in the DOS header
//
if( (ReadFile(hFile, &dosHdr, sizeof(dosHdr), &cb, 0) == FALSE)
|| (cb != sizeof(dosHdr)) )
{
printf("Failed to read DOS header!/n");
CloseHandle(hFile);
return;
}
//
// Seek the PE header
//
if( (dosHdr.e_magic != IMAGE_DOS_SIGNATURE) ||
(SetFilePointer(hFile, dosHdr.e_lfanew, 0, FILE_BEGIN) == -1L) )
{
printf("Failed to read NT header!/n");
CloseHandle(hFile);
return;
}
//
// Read in the NT header
//
if( (!ReadFile(hFile, &ntHdr, sizeof(ntHdr), &cb, 0))
|| (cb != sizeof(ntHdr)) )
{
printf("Failed to read NT header!/n");
CloseHandle(hFile);
return;
}
//
// Search the PE sisnature
//
if(ntHdr.Signature != IMAGE_NT_SIGNATURE)
{
printf("The file is not a valid PE file!/n");
CloseHandle(hFile);
return;
}
//
// Check if the PE file's checksum need adjusted
//
if(ntHdr.OptionalHeader.CheckSum == dwCheckSum)
{
printf("The PE file CheckSum needn't to be adjusted/n");
CloseHandle(hFile);
return;
}
//
// Seek the PE header
//
if( SetFilePointer(hFile, dosHdr.e_lfanew, 0, FILE_BEGIN) == -1L )
{
printf("Failed to locate PE header!/n");
CloseHandle(hFile);
return;
}
printf("Old Checksum = 0x%08X/n", ntHdr.OptionalHeader.CheckSum);
printf("New Checksum = 0x%08X/n", dwCheckSum);
//
// Modify the CheckSum
//
ntHdr.OptionalHeader.CheckSum = dwCheckSum;
if( !WriteFile(hFile, &ntHdr, sizeof(ntHdr), &cb, NULL) )
{
printf("Failed to Adjust Checksum!/n");
}
else
{
printf("Adjust Checksum successfully!/n");
}
CloseHandle(hFile);
return;
}
__inline void PrintUsage( void )
{
printf("PE File CheckSum Adjust Utility v1.00/n"
"Written by LengShengkui, 2002-09-16/n/n"
" Usage: PECHKSUM <PE filename>/n");
}