Introduction
This is a simple shell script to XOR hex strings. I used it to generate sha1 hashes of files and XOR ing their hashes to create master result.
The Code
function xor()
{
local res=(`echo "$1" | sed "s/../0x& /g"`)
shift 1
while [[ "$1" ]]; do
local one=(`echo "$1" | sed "s/../0x& /g"`)
local count1=${#res[@]}
if [ $count1 -lt ${#one[@]} ]
then
count1=${#one[@]}
fi
for (( i = 0; i < $count1; i++ ))
do
res[$i]=$((${one[$i]:-0} ^ ${res[$i]:-0}))
done
shift 1
done
printf "%02x" "${res[@]}"
}
Sample Run
xor af36a125944af4682a239f2a5e35f5f91c671abe 249fecfe9fbfb5920f19e198944c788f5d7c64c9
Output
8ba94ddb0bf541fa253a7eb2ca798d76411b7e77
Now let's see what this function does.
- Convert the first argument to an array of hex bytes by adding space and 0x after every two characters
- Loop through each argument
- Convert argument to array of hex values
- Get the maximum number of arguments between two arrays
- Loop through each array element and XOR values and store in result
- In the end, print hex values
Nice and simple now. This program can be used to XOR hash values of several files to generate a master result, i.e., XORed hashes.
Points of Interest
I've mostly worked on Windows environment, so this is my first hands on shell script in Linux. This also shows how to use loops, conditions, arrays.