Click here to Skip to main content
Click here to Skip to main content

XOR Hex Strings in Linux Shell Script

, 4 Oct 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
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

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)

Share

About the Author

Sanjay1982
Software Developer
India India
I have been involved in C, C++ development for over a six year now. I have worked on projects involving games, insurance application, stats and reporting applications. Being busy with work I hardly got time to post my own articles but now I am getting more involved. I don't promise much but hopefully you'll see some more interesting articles from me in near future.

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.141223.1 | Last Updated 4 Oct 2012
Article Copyright 2012 by Sanjay1982
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid