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
For installation and learning resources, refer to the Ruby resources page.
For running the tests provided, you will need the Minitest gem. Open a terminal window and run the following command to install minitest:
gem install minitest
If you would like color output, you can require 'minitest/pride'
in
the test file, or note the alternative instruction, below, for running
the test file.
Run the tests from the exercise directory using the following command:
ruby affine_cipher_test.rb
To include color from the command line:
ruby -r minitest/pride affine_cipher_test.rb
Wikipedia http://en.wikipedia.org/wiki/Affine_cipher
It's possible to submit an incomplete solution so you can see how others have completed the exercise.
require 'minitest/autorun'
require_relative 'affine_cipher'
# Common test data version: 2.0.0 8026923
class AffineCipherTest < Minitest::Test
def test_encode_yes
# skip
cipher = Affine.new(5, 7)
plaintext = 'yes'
ciphertext = 'xbt'
assert_equal ciphertext, cipher.encode(plaintext)
end
def test_encode_no
skip
cipher = Affine.new(15, 18)
plaintext = 'no'
ciphertext = 'fu'
assert_equal ciphertext, cipher.encode(plaintext)
end
def test_encode_omg
skip
cipher = Affine.new(21, 3)
plaintext = 'OMG'
ciphertext = 'lvz'
assert_equal ciphertext, cipher.encode(plaintext)
end
def test_encode_o_m_g
skip
cipher = Affine.new(25, 47)
plaintext = 'O M G'
ciphertext = 'hjp'
assert_equal ciphertext, cipher.encode(plaintext)
end
def test_encode_mindblowingly
skip
cipher = Affine.new(11, 15)
plaintext = 'mindblowingly'
ciphertext = 'rzcwa gnxzc dgt'
assert_equal ciphertext, cipher.encode(plaintext)
end
def test_encode_numbers
skip
cipher = Affine.new(3, 4)
plaintext = 'Testing,1 2 3, testing.'
ciphertext = 'jqgjc rw123 jqgjc rw'
assert_equal ciphertext, cipher.encode(plaintext)
end
def test_encode_deep_thought
skip
cipher = Affine.new(5, 17)
plaintext = 'Truth is fiction.'
ciphertext = 'iynia fdqfb ifje'
assert_equal ciphertext, cipher.encode(plaintext)
end
def test_encode_all_the_letters
skip
cipher = Affine.new(17, 33)
plaintext = 'The quick brown fox jumps over the lazy dog.'
ciphertext = 'swxtj npvyk lruol iejdc blaxk swxmh qzglf'
assert_equal ciphertext, cipher.encode(plaintext)
end
def test_encode_with_a_not_coprime_to_m
skip
assert_raises(ArgumentError) { Affine.new(6, 17) }
end
def test_decode_exercism
skip
cipher = Affine.new(3, 7)
ciphertext = 'tytgn fjr'
plaintext = 'exercism'
assert_equal plaintext, cipher.decode(ciphertext)
end
def test_decode_a_sentence
skip
cipher = Affine.new(19, 16)
ciphertext = 'qdwju nqcro muwhn odqun oppmd aunwd o'
plaintext = 'anobstacleisoftenasteppingstone'
assert_equal plaintext, cipher.decode(ciphertext)
end
def test_decode_numbers
skip
cipher = Affine.new(25, 7)
ciphertext = 'odpoz ub123 odpoz ub'
plaintext = 'testing123testing'
assert_equal plaintext, cipher.decode(ciphertext)
end
def test_decode_all_the_letters
skip
cipher = Affine.new(17, 33)
ciphertext = 'swxtj npvyk lruol iejdc blaxk swxmh qzglf'
plaintext = 'thequickbrownfoxjumpsoverthelazydog'
assert_equal plaintext, cipher.decode(ciphertext)
end
def test_decode_with_no_spaces_in_input
skip
cipher = Affine.new(17, 33)
ciphertext = 'swxtjnpvyklruoliejdcblaxkswxmhqzglf'
plaintext = 'thequickbrownfoxjumpsoverthelazydog'
assert_equal plaintext, cipher.decode(ciphertext)
end
def test_decode_with_too_many_spaces
skip
cipher = Affine.new(15, 16)
ciphertext = 'vszzm cly yd cg qdp'
plaintext = 'jollygreengiant'
assert_equal plaintext, cipher.decode(ciphertext)
end
def test_decode_with_a_not_coprime_to_m
skip
assert_raises(ArgumentError) { Affine.new(13, 5) }
end
end
# frozen_string_literal: true
class Affine
ALPHABET = "abcdefghijklmnopqrstuvwxyz"
private_constant :ALPHABET
CHUNKS_OF_5 = /.{1,5}/.freeze
private_constant :CHUNKS_OF_5
IS_COPRIME = ->(a_key) { a_key.gcd(ALPHABET.length) == 1 }
private_constant :IS_COPRIME
NON_WORD_CHARACTERS = /\W/.freeze
private_constant :NON_WORD_CHARACTERS
def initialize(a_key, b_key)
raise ArgumentError unless IS_COPRIME.call(a_key)
@key = generate_key(a_key, b_key)
end
def encode(plaintext)
plaintext
.downcase
.gsub(NON_WORD_CHARACTERS, "")
.tr(ALPHABET, key)
.scan(CHUNKS_OF_5)
.join(" ")
end
def decode(ciphertext)
ciphertext
.gsub(NON_WORD_CHARACTERS, "")
.tr(key, ALPHABET)
end
private
attr_reader :key
def generate_key(*keys)
ALPHABET
.chars
.each_index
.with_object(keys)
.reduce("", &method(:affine_character))
end
def affine_character(acc, (index, (a_key, b_key)))
# (ax + b) mod m
affine_index = (a_key * index + b_key) % ALPHABET.length
acc + ALPHABET[affine_index]
end
end
A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.
Here are some questions to help you reflect on this solution and learn the most from it.
Level up your programming skills with 3,373 exercises across 50 languages, and insightful discussion with our volunteer team of welcoming mentors. Exercism is 100% free forever.
Sign up Learn More
Community comments