MCPcopy Create free account
hub / github.com/ELMERIKH/PyinMemoryPE / generate_checksum

Method generate_checksum

pythonmemorymodule/pefile.py:7164–7210  ·  view source on GitHub ↗
(self)

Source from the content-addressed store, hash-verified

7162 return self.OPTIONAL_HEADER.CheckSum == self.generate_checksum()
7163
7164 def generate_checksum(self):
7165 # This will make sure that the data representing the PE image
7166 # is updated with any changes that might have been made by
7167 # assigning values to header fields as those are not automatically
7168 # updated upon assignment.
7169 #
7170 # data = self.write()
7171 # print('{0}'.format(len(data)))
7172 # for idx, b in enumerate(data):
7173 # if b != ord(self.__data__[idx]) or (idx > 1244440 and idx < 1244460):
7174 # print('Idx: {0} G {1:02x} {3} B {2:02x}'.format(
7175 # idx, ord(self.__data__[idx]), b,
7176 # self.__data__[idx], chr(b)))
7177 self.__data__ = self.write()
7178
7179 # Get the offset to the CheckSum field in the OptionalHeader
7180 # (The offset is the same in PE32 and PE32+)
7181 checksum_offset = self.OPTIONAL_HEADER.get_file_offset() + 0x40 # 64
7182
7183 checksum = 0
7184 # Verify the data is dword-aligned. Add padding if needed
7185 #
7186 remainder = len(self.__data__) % 4
7187 data_len = len(self.__data__) + ((4 - remainder) * (remainder != 0))
7188
7189 for i in range(int(data_len / 4)):
7190 # Skip the checksum field
7191 if i == int(checksum_offset / 4):
7192 continue
7193 if i + 1 == (int(data_len / 4)) and remainder:
7194 dword = struct.unpack(
7195 "I", self.__data__[i * 4 :] + (b"\0" * (4 - remainder))
7196 )[0]
7197 else:
7198 dword = struct.unpack("I", self.__data__[i * 4 : i * 4 + 4])[0]
7199 # Optimized the calculation (thanks to Emmanuel Bourg for pointing it out!)
7200 checksum += dword
7201 if checksum >= 2**32:
7202 checksum = (checksum & 0xFFFFFFFF) + (checksum >> 32)
7203
7204 checksum = (checksum & 0xFFFF) + (checksum >> 16)
7205 checksum = (checksum) + (checksum >> 16)
7206 checksum = checksum & 0xFFFF
7207
7208 # The length is the one of the original data, not the padded one
7209 #
7210 return checksum + len(self.__data__)
7211
7212 def is_exe(self):
7213 """Check whether the file is a standard executable.

Callers 1

verify_checksumMethod · 0.95

Calls 3

writeMethod · 0.95
get_file_offsetMethod · 0.80
unpackMethod · 0.45

Tested by

no test coverage detected