Created
July 20, 2013 13:48
-
-
Save EarlGray/6045085 to your computer and use it in GitHub Desktop.
Patching binary files with bash and xxd
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
#!/bin/bash | |
export CHECKSUM_AT=148 | |
function joinlines { | |
while read line ; do | |
echo -n "$line" | |
done | |
} | |
function split-by { | |
read input | |
while [ "$input" ]; do | |
echo ${input:0:$1} | |
input=${input:$1} | |
done | |
} | |
function strrep { | |
read _where | |
local _with=$1 | |
local _at=$2 | |
local _pre=${_where:0:$_at} | |
local _post=${_where:$(($_at + ${#_with}))} | |
echo "${_pre}${_with}${_post}" | |
} | |
function checksum { | |
local sum=0 | |
read input | |
echo "checksum input length is ${#input}" | |
while [ "$input" ] ; do | |
byte="0x${input:0:2}" | |
sum=$(($sum + $byte)) | |
input=${input:2} | |
done | |
printf "0%o\n" $sum | |
} | |
function makedump { | |
xxd -p $1 | joinlines | |
} | |
function fromdump { | |
split-by 64 | xxd -r -p | |
} | |
function checksummable { | |
cat | strrep "2020202020202020" $((2 * $CHECKSUM_AT)) | |
} | |
function take { | |
dd bs=1 count=$((2 * $1)) status=noxfer | |
} | |
function from_ascii { | |
echo $1 | xxd -p | |
} | |
function patch-bin { | |
makedump $1 | strrep "$2" $((2 * $3)) | fromdump | |
} | |
function tar-checksum { | |
cat $1 | makedump | take 512 | checksummable | checksum | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment