Created
November 3, 2021 01:57
-
-
Save akkuman/572911e0ea0872e1e67b6c7fe8056b8f to your computer and use it in GitHub Desktop.
纯golang计算pe的checksum #pe #golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/binary" | |
"fmt" | |
"math" | |
"os" | |
) | |
func GeneratePECheckSum(fileBytes []byte) uint32 { | |
// get checksum offset | |
ntHeaderOffsetBytes := fileBytes[0x3C:0x40] | |
ntHeaderOffset := binary.LittleEndian.Uint32(ntHeaderOffsetBytes) | |
checksumOffset := ntHeaderOffset + 0x58 | |
var checksum uint64 = 0 | |
top := uint64(math.Pow(2, 32)) | |
for i := 0; i < len(fileBytes)/4; i++ { | |
if i == int(checksumOffset/4) { | |
continue | |
} | |
dword := binary.LittleEndian.Uint32(fileBytes[i*4 : (i*4)+4]) | |
checksum = (checksum & 0xffffffff) + uint64(dword) + (checksum >> 32) | |
if checksum > top { | |
checksum = (checksum & 0xffffffff) + (checksum >> 32) | |
} | |
} | |
checksum = (checksum & 0xffff) + (checksum >> 16) | |
checksum = (checksum) + (checksum >> 16) | |
checksum = checksum & 0xffff | |
checksum += uint64(len(fileBytes)) | |
return uint32(checksum) | |
} | |
func main() { | |
fileBytes, err := os.ReadFile(os.Args[1]) | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
fmt.Printf("checksum: %x\n", GeneratePECheckSum(fileBytes)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment