Skip to content

Instantly share code, notes, and snippets.

@wuthmone
Created August 28, 2016 09:23
Show Gist options
  • Save wuthmone/c8aed1eb721b8588d0b3d5ba41030005 to your computer and use it in GitHub Desktop.
Save wuthmone/c8aed1eb721b8588d0b3d5ba41030005 to your computer and use it in GitHub Desktop.
#!/bin/bash
function printMatrix {
A=( $@ )
for j in {0..1}
do
i=$j
echo -n "|"
while [ $i -lt ${#A[@]} ] ; do
printf " %2d " ${A[$i]}
i=$(($i+2))
done
echo "|"
done
}
#Let the key = FIRD
K=( 5 8 17 3 )
function matrixInverse {
#Evaluating the determinant
# | | | |
# | A C | | K[0] K[2] |
# det K = | | = AD - BC = | |
# | B D | | K[1] K[3] |
# | | | |
det=$(( ${K[0]} * ${K[3]} - ${K[1]} * ${K[2]} ))
#Negative modulo correction
# All -ve +ve
# | | |
# | | |
# V V V
det=$(( ( ( $det % 26 ) + 26 ) % 26 ))
echo 1/det = 1/$det
if [[ $(( $det % 2 )) == 0 || $(( $det % 13 )) == 0 ]]
then
echo "Decryption not possible"
exit 1
fi
#Finding 1/$det mod 26 = x
#Therefore $det * x = 1 mod 26
rem=0
x=-1
while [ $rem != 1 ] ; do
x=$(($x+2))
rem=$(( $(( $det * $x )) % 26 ))
done
# ^
# |
# |
# Always +ve
echo 1/$det mod 26 = $x
##### K = ( ${K[3]} -${K[1]} -${K[2]} ${K[0]} )
K=( $((( ${K[3]} * $x )%26)) $((((( -${K[1]} * $x )%26)+26)%26 )) $((((( -${K[2]} * $x )%26)+26)%26 )) $((( ${K[0]} * $x )%26)) )
}
echo Original Key: FIRD
echo
printMatrix ${K[@]}
echo
matrixInverse
echo
echo Inverse Key
echo
printMatrix ${K[@]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment