Create an implementation of the affine cipher, an ancient encryption system created in the Middle East.
The affine cipher is a type of monoalphabetic substitution cipher. Each character is mapped to its numeric equivalent, encrypted with a mathematical function and then converted to the letter relating to its new numeric value. Although all monoalphabetic ciphers are weak, the affine cypher is much stronger than the atbash cipher, because it has many more keys.
The encryption function is:
E(x) = (ax + b) mod m
x
is the letter's index from 0 - length of alphabet - 1m
is the length of the alphabet. For the roman alphabet m == 26
.a
and b
make the keyThe decryption function is:
D(y) = a^-1(y - b) mod m
y
is the numeric value of an encrypted letter, ie. y = E(x)
a^-1
is the modular multiplicative inverse
of a mod m
a
only exists if a
and m
are
coprime.To find the MMI of a
:
an mod m = 1
n
is the modular multiplicative inverse of a mod m
More information regarding how to find a Modular Multiplicative Inverse and what it means can be found here.
Because automatic decryption fails if a
is not coprime to m
your
program should return status 1 and "Error: a and m must be coprime."
if they are not. Otherwise it should encode or decode with the
provided key.
The Caesar (shift) cipher is a simple affine cipher where a
is 1 and
b
as the magnitude results in a static displacement of the letters.
This is much less secure than a full implementation of the affine cipher.
Ciphertext is written out in groups of fixed length, the traditional group size being 5 letters, and punctuation is excluded. This is to make it harder to guess things based on word boundaries.
test
gives ybty
with the key a=5 b=7ybty
gives test
with the key a=5 b=7ybty
gives lqul
with the wrong key a=11 b=7kqlfd jzvgy tpaet icdhm rtwly kqlon ubstx
thequickbrownfoxjumpsoverthelazydog
with the key a=19 b=13test
with the key a=18 b=13
Error: a and m must be coprime.
9 mod 26 = 9
9 * 3 mod 26 = 27 mod 26 = 1
3
is the MMI of 9 mod 26
15 mod 26 = 15
15 * 7 mod 26 = 105 mod 26 = 1
7
is the MMI of 15 mod 26
Simply type make chez
if you're using ChezScheme or make guile
if you're using GNU Guile.
Sometimes the name for the scheme binary on your system will differ from the defaults.
When this is the case, you'll need to tell make by running make chez chez=your-chez-binary
or make guile guile=your-guile-binary
.
(load "test.scm")
at the repl prompt.affine-cipher.scm
reloading as you go.(test)
to check your solution.If some of the test cases fail, you should see the failing input and the expected output.
The failing input is presented as a list because the tests call your solution by (apply affine-cipher input-list)
.
To learn more about apply
see The Scheme Programming Language -- Chapter 5
Sign up to Exercism to learn and master Scheme with 39 exercises, and real human mentoring, all for free.