Skip to content

Instantly share code, notes, and snippets.

@akkuman
Created November 3, 2021 01:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akkuman/572911e0ea0872e1e67b6c7fe8056b8f to your computer and use it in GitHub Desktop.
Save akkuman/572911e0ea0872e1e67b6c7fe8056b8f to your computer and use it in GitHub Desktop.
纯golang计算pe的checksum #pe #golang
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