Methods to hex edit binary files via Powershell

2019-01-24 10:04发布

Am trying to perform binary hex edit from the command line using only powershell. Have had partial success performing a hex replace with this snip. Problem springs up when 123456 occurs multiple times and the replacement was only supposed to occur at a specific location.

NOTE: The snip requires the Convert-ByteArrayToHexString and Convert-HexStringToByteArray functions found here.

http://www.sans.org/windows-security/2010/02/11/powershell-byte-array-hex-convert

$readin = [System.IO.File]::ReadAllBytes("C:\OldFile.exe");
$hx = Convert-ByteArrayToHexString $readin -width 40 -delimiter "";
$hx = $hx -replace "123456","FFFFFF";
$hx = "0x" + $hx;
$writeout = Convert-HexStringToByteArray $hx;
set-content -value $writeout -encoding byte -path "C:\NewFile.exe";

How can we specify an offset position into powershell to replace this sketchy -replace command.

2条回答
We Are One
2楼-- · 2019-01-24 10:45

Probably the way most idiomatic to PowerShell would be:

$offset = 0x3C
[byte[]]$bytes = Get-Content C:\OldFile.exe -Encoding Byte

$bytes[$offset++] = 0xFF
$bytes[$offset++] = 0xFF
$bytes[$offset] = 0xFF

$bytes |Set-Content C:\NewFile.exe -Encoding Byte
查看更多
乱世女痞
3楼-- · 2019-01-24 11:06

You already have a byte array, so you could simply modify the bytes at any given offset.

$bytes  = [System.IO.File]::ReadAllBytes("C:\OldFile.exe")
$offset = 23

$bytes[$offset]   = 0xFF
$bytes[$offset+1] = 0xFF
$bytes[$offset+2] = 0xFF

[System.IO.File]::WriteAllBytes("C:\NewFile.exe", $bytes)
查看更多
登录 后发表回答