Skip to content

Commit

Permalink
Add affine-cipher practice exercise (#515)
Browse files Browse the repository at this point in the history
  • Loading branch information
ryanplusplus authored Sep 21, 2024
1 parent efd94a5 commit 9df4ae4
Show file tree
Hide file tree
Showing 9 changed files with 346 additions and 0 deletions.
8 changes: 8 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -1367,6 +1367,14 @@
"practices": [],
"prerequisites": [],
"difficulty": 3
},
{
"slug": "affine-cipher",
"name": "Affine Cipher",
"uuid": "e3a84895-fb1b-4d03-b56a-84cb00b3cf93",
"practices": [],
"prerequisites": [],
"difficulty": 5
}
]
},
Expand Down
5 changes: 5 additions & 0 deletions exercises/practice/affine-cipher/.busted
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
return {
default = {
ROOT = { '.' }
}
}
74 changes: 74 additions & 0 deletions exercises/practice/affine-cipher/.docs/instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# Instructions

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 cipher is much stronger than the atbash cipher, because it has many more keys.

[//]: # " monoalphabetic as spelled by Merriam-Webster, compare to polyalphabetic "

## Encryption

The encryption function is:

```text
E(x) = (ai + b) mod m
```

Where:

- `i` is the letter's index from `0` to the length of the alphabet - 1.
- `m` is the length of the alphabet.
For the Roman alphabet `m` is `26`.
- `a` and `b` are integers which make up the encryption key.

Values `a` and `m` must be _coprime_ (or, _relatively prime_) for automatic decryption to succeed, i.e., they have number `1` as their only common factor (more information can be found in the [Wikipedia article about coprime integers][coprime-integers]).
In case `a` is not coprime to `m`, your program should indicate that this is an error.
Otherwise it should encrypt or decrypt with the provided key.

For the purpose of this exercise, digits are valid input but they are not encrypted.
Spaces and punctuation characters are excluded.
Ciphertext is written out in groups of fixed length separated by space, the traditional group size being `5` letters.
This is to make it harder to guess encrypted text based on word boundaries.

## Decryption

The decryption function is:

```text
D(y) = (a^-1)(y - b) mod m
```

Where:

- `y` is the numeric value of an encrypted letter, i.e., `y = E(x)`
- it is important to note that `a^-1` is the modular multiplicative inverse (MMI) of `a mod m`
- the modular multiplicative inverse only exists if `a` and `m` are coprime.

The MMI of `a` is `x` such that the remainder after dividing `ax` by `m` is `1`:

```text
ax mod m = 1
```

More information regarding how to find a Modular Multiplicative Inverse and what it means can be found in the [related Wikipedia article][mmi].

## General Examples

- Encrypting `"test"` gives `"ybty"` with the key `a = 5`, `b = 7`
- Decrypting `"ybty"` gives `"test"` with the key `a = 5`, `b = 7`
- Decrypting `"ybty"` gives `"lqul"` with the wrong key `a = 11`, `b = 7`
- Decrypting `"kqlfd jzvgy tpaet icdhm rtwly kqlon ubstx"` gives `"thequickbrownfoxjumpsoverthelazydog"` with the key `a = 19`, `b = 13`
- Encrypting `"test"` with the key `a = 18`, `b = 13` is an error because `18` and `26` are not coprime

## Example of finding a Modular Multiplicative Inverse (MMI)

Finding MMI for `a = 15`:

- `(15 * x) mod 26 = 1`
- `(15 * 7) mod 26 = 1`, ie. `105 mod 26 = 1`
- `7` is the MMI of `15 mod 26`

[mmi]: https://en.wikipedia.org/wiki/Modular_multiplicative_inverse
[coprime-integers]: https://en.wikipedia.org/wiki/Coprime_integers
19 changes: 19 additions & 0 deletions exercises/practice/affine-cipher/.meta/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"authors": [
"ryanplusplus"
],
"files": {
"solution": [
"affine-cipher.lua"
],
"test": [
"affine-cipher_spec.lua"
],
"example": [
".meta/example.lua"
]
},
"blurb": "Create an implementation of the Affine cipher, an ancient encryption algorithm from the Middle East.",
"source": "Wikipedia",
"source_url": "https://en.wikipedia.org/wiki/Affine_cipher"
}
48 changes: 48 additions & 0 deletions exercises/practice/affine-cipher/.meta/example.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
local M = 26

local function coprime(x, y)
while y ~= 0 do
x, y = y, x % y
end
return x == 1
end

local function partition(s)
return s:gsub('.....', '%0 '):gsub(' $', '')
end

local function mmi(x, mod)
local mmi = 1
while (x * mmi) % mod ~= 1 do
mmi = mmi + 1
end
return mmi
end

local function encode_char(char, key)
local x = char:byte() - ('a'):byte()
return string.char((key.a * x + key.b) % M + ('a'):byte())
end

local function decode_char(char, key)
local x = char:byte() - ('a'):byte()
return string.char((mmi(key.a, M) * (x - key.b)) % M + ('a'):byte())
end

local function encode(phrase, key)
assert(coprime(key.a, M), 'a and m must be coprime.')

return partition(phrase:gsub('%W', ''):gsub('%a', function(char)
return encode_char(char:lower(), key)
end))
end

local function decode(phrase, key)
assert(coprime(key.a, M), 'a and m must be coprime.')

return phrase:gsub('%s', ''):gsub('%a', function(char)
return decode_char(char:lower(), key)
end)
end

return { encode = encode, decode = decode }
20 changes: 20 additions & 0 deletions exercises/practice/affine-cipher/.meta/spec_generator.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
return {
module_name = 'affine_cipher',

generate_test = function(case)
if type(case.expected) == 'string' then
local template = [[
local phrase = '%s'
local expected = '%s'
assert.are.same(expected, affine_cipher.%s(phrase, { a = %d, b = %d }))]]
return template:format(case.input.phrase, case.expected, case.property, case.input.key.a, case.input.key.b)
else
local template = [[
local phrase = '%s'
assert.has.error(function()
affine_cipher.%s(phrase, { a = %d, b = %d })
end, '%s')]]
return template:format(case.input.phrase, case.property, case.input.key.a, case.input.key.b, case.expected.error)
end
end
}
58 changes: 58 additions & 0 deletions exercises/practice/affine-cipher/.meta/tests.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# This is an auto-generated file.
#
# Regenerating this file via `configlet sync` will:
# - Recreate every `description` key/value pair
# - Recreate every `reimplements` key/value pair, where they exist in problem-specifications
# - Remove any `include = true` key/value pair (an omitted `include` key implies inclusion)
# - Preserve any other key/value pair
#
# As user-added comments (using the # character) will be removed when this file
# is regenerated, comments can be added via a `comment` key.

[2ee1d9af-1c43-416c-b41b-cefd7d4d2b2a]
description = "encode -> encode yes"

[785bade9-e98b-4d4f-a5b0-087ba3d7de4b]
description = "encode -> encode no"

[2854851c-48fb-40d8-9bf6-8f192ed25054]
description = "encode -> encode OMG"

[bc0c1244-b544-49dd-9777-13a770be1bad]
description = "encode -> encode O M G"

[381a1a20-b74a-46ce-9277-3778625c9e27]
description = "encode -> encode mindblowingly"

[6686f4e2-753b-47d4-9715-876fdc59029d]
description = "encode -> encode numbers"

[ae23d5bd-30a8-44b6-afbe-23c8c0c7faa3]
description = "encode -> encode deep thought"

[c93a8a4d-426c-42ef-9610-76ded6f7ef57]
description = "encode -> encode all the letters"

[0673638a-4375-40bd-871c-fb6a2c28effb]
description = "encode -> encode with a not coprime to m"

[3f0ac7e2-ec0e-4a79-949e-95e414953438]
description = "decode -> decode exercism"

[241ee64d-5a47-4092-a5d7-7939d259e077]
description = "decode -> decode a sentence"

[33fb16a1-765a-496f-907f-12e644837f5e]
description = "decode -> decode numbers"

[20bc9dce-c5ec-4db6-a3f1-845c776bcbf7]
description = "decode -> decode all the letters"

[623e78c0-922d-49c5-8702-227a3e8eaf81]
description = "decode -> decode with no spaces in input"

[58fd5c2a-1fd9-4563-a80a-71cff200f26f]
description = "decode -> decode with too many spaces"

[b004626f-c186-4af9-a3f4-58f74cdb86d5]
description = "decode -> decode with a not coprime to m"
9 changes: 9 additions & 0 deletions exercises/practice/affine-cipher/affine-cipher.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
local function encode(phrase, key)

end

local function decode(phrase, key)

end

return { encode = encode, decode = decode }
105 changes: 105 additions & 0 deletions exercises/practice/affine-cipher/affine-cipher_spec.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
local affine_cipher = require('affine-cipher')

describe('affine-cipher', function()
describe('encode', function()
it('encode yes', function()
local phrase = 'yes'
local expected = 'xbt'
assert.are.same(expected, affine_cipher.encode(phrase, { a = 5, b = 7 }))
end)

it('encode no', function()
local phrase = 'no'
local expected = 'fu'
assert.are.same(expected, affine_cipher.encode(phrase, { a = 15, b = 18 }))
end)

it('encode omg', function()
local phrase = 'OMG'
local expected = 'lvz'
assert.are.same(expected, affine_cipher.encode(phrase, { a = 21, b = 3 }))
end)

it('encode o m g', function()
local phrase = 'O M G'
local expected = 'hjp'
assert.are.same(expected, affine_cipher.encode(phrase, { a = 25, b = 47 }))
end)

it('encode mindblowingly', function()
local phrase = 'mindblowingly'
local expected = 'rzcwa gnxzc dgt'
assert.are.same(expected, affine_cipher.encode(phrase, { a = 11, b = 15 }))
end)

it('encode numbers', function()
local phrase = 'Testing,1 2 3, testing.'
local expected = 'jqgjc rw123 jqgjc rw'
assert.are.same(expected, affine_cipher.encode(phrase, { a = 3, b = 4 }))
end)

it('encode deep thought', function()
local phrase = 'Truth is fiction.'
local expected = 'iynia fdqfb ifje'
assert.are.same(expected, affine_cipher.encode(phrase, { a = 5, b = 17 }))
end)

it('encode all the letters', function()
local phrase = 'The quick brown fox jumps over the lazy dog.'
local expected = 'swxtj npvyk lruol iejdc blaxk swxmh qzglf'
assert.are.same(expected, affine_cipher.encode(phrase, { a = 17, b = 33 }))
end)

it('encode with a not coprime to m', function()
local phrase = 'This is a test.'
assert.has.error(function()
affine_cipher.encode(phrase, { a = 6, b = 17 })
end, 'a and m must be coprime.')
end)
end)

describe('decode', function()
it('decode exercism', function()
local phrase = 'tytgn fjr'
local expected = 'exercism'
assert.are.same(expected, affine_cipher.decode(phrase, { a = 3, b = 7 }))
end)

it('decode a sentence', function()
local phrase = 'qdwju nqcro muwhn odqun oppmd aunwd o'
local expected = 'anobstacleisoftenasteppingstone'
assert.are.same(expected, affine_cipher.decode(phrase, { a = 19, b = 16 }))
end)

it('decode numbers', function()
local phrase = 'odpoz ub123 odpoz ub'
local expected = 'testing123testing'
assert.are.same(expected, affine_cipher.decode(phrase, { a = 25, b = 7 }))
end)

it('decode all the letters', function()
local phrase = 'swxtj npvyk lruol iejdc blaxk swxmh qzglf'
local expected = 'thequickbrownfoxjumpsoverthelazydog'
assert.are.same(expected, affine_cipher.decode(phrase, { a = 17, b = 33 }))
end)

it('decode with no spaces in input', function()
local phrase = 'swxtjnpvyklruoliejdcblaxkswxmhqzglf'
local expected = 'thequickbrownfoxjumpsoverthelazydog'
assert.are.same(expected, affine_cipher.decode(phrase, { a = 17, b = 33 }))
end)

it('decode with too many spaces', function()
local phrase = 'vszzm cly yd cg qdp'
local expected = 'jollygreengiant'
assert.are.same(expected, affine_cipher.decode(phrase, { a = 15, b = 16 }))
end)

it('decode with a not coprime to m', function()
local phrase = 'Test'
assert.has.error(function()
affine_cipher.decode(phrase, { a = 13, b = 5 })
end, 'a and m must be coprime.')
end)
end)
end)

0 comments on commit 9df4ae4

Please sign in to comment.