Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / shell

XOR Hex Strings in Linux Shell Script

0.00/5 (No votes)
4 Oct 2012CPOL 24K  
Small shell script function to XOR hex strings

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

VBScript
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.

  1. Convert the first argument to an array of hex bytes by adding space and 0x after every two characters
  2. Loop through each argument
  3. Convert argument to array of hex values
  4. Get the maximum number of arguments between two arrays
  5. Loop through each array element and XOR values and store in result
  6. 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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)