bashencryptionscriptingvigenere

Vigenère cipher decryption


I'm trying to make encryption and decryption with a Vigenère cipher.

It's a part of a greater task where the Vigenère cipher plays a small part. I got this encryption script from bash to work. The problem is how i get to use the same code in reverse to decrypt the code.

#!/usr/local/bin/bash
# vigenere.sh
# http://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher

a="ABCDEFGHIJKLMNOPQRSTUVWXYZ"

[[ "${*/-d/}" != "" ]] &&
echo "Usage: $0 [-d]" && exit 1
m=${1:+-}

printf "string: ";read t
printf "keyphrase: ";read -s k
printf "\n"
for ((i=0;i<${#t};i++)); do
  p1=${a%%${t:$i:1}*}
  p2=${a%%${k:$((i%${#k})):1}*}
  d="${d}${a:$(((${#p1}${m:-+}${#p2})%${#a})):1}"
done
echo "$d"

Solution

  • To see what it does just launch it with bash -x option set, for example if script is saved in vig.sh:

    bash -x vig.sh
    

    basically, a to store the uppercase alphabet

    -d, is an optional parameter to decrypt when set m will bet set to -

    this reads from input t to store the source string, k the key

    printf "string: ";read t
    printf "keyphrase: ";read -s k
    

    the following makes a loop over character indices of variable t

    for ((i=0;i<${#t};i++)); do
    

    p1 contains the alphabet with the suffix begining with current character from t removed

    p1=${a%%${t:$i:1}*}
    

    p2 does the same with current character from key (with a modulo to avoid out of bounds)

    then the sum or difference (when -d option is set) between p1 and p2 lengths is used to get the character in alphabet and appended to d.

    Examples

    vig.sh
    string: HELLOWORLD
    keyphrase: FOO
    -> MSZQCKTFZI
    
    vig.sh -d
    string: MSZQCKTFZI
    keyphrase: FOO
    -> HELLOWORLD