

Task

Implement a Caesar cipher, both encoding and decoding. 

The key is an integer from 1 to 25.

This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).

The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).

So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".

This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.

Caesar cipher is identical to Vigenère cipher with a key of length 1. 

Also, Rot-13 is identical to Caesar cipher with key 13.



Related tasks

 Rot-13
 Substitution Cipher
 Vigenère Cipher/Cryptanalysis


caesar() {
    local OPTIND
    local encrypt n=0
    while getopts :edn: option; do
        case $option in
            e) encrypt=true ;;
            d) encrypt=false ;;
            n) n=$OPTARG ;;
            :) echo "error: missing argument for -$OPTARG" >&2
               return 1 ;;
            ?) echo "error: unknown option -$OPTARG" >&2
               return 1 ;;
        esac
    done
    shift $((OPTIND-1))
    if [[ -z $encrypt ]]; then
        echo "error: specify one of -e or -d" >&2
        return 1
    fi
 
    local upper=ABCDEFGHIJKLMNOPQRSTUVWXYZ
    local lower=abcdefghijklmnopqrstuvwxyz
    if $encrypt; then
        tr "$upper$lower" "${upper:n}${upper:0:n}${lower:n}${lower:0:n}" <<< "$1"
    else
        tr "${upper:n}${upper:0:n}${lower:n}${lower:0:n}" "$upper$lower" <<< "$1"
    fi
}
 
tr() {
    local -A charmap
    local i trans line char
    for ((i=0; i<${#1}; i++)); do
        charmap[${1:i:1}]=${2:i:1}
    done
    while IFS= read -r line; do
        trans=""
        for ((i=0; i<${#line}; i++)); do
            char=${line:i:1}
            if [[ -n ${charmap[$char]} ]]; then
                trans+=${charmap[$char]}
            else
                trans+=$char
            fi
        done
        echo "$trans"
    done
}
 
txt="The five boxing wizards jump quickly."
enc=$(caesar -e -n 5 "$txt")
dec=$(caesar -d -n 5 "$enc")
 
echo "original:  $txt"
echo "encrypted: $enc"
echo "decrypted: $dec"