Skip to content

Commit

Permalink
Sync affine-cipher (exercism#841)
Browse files Browse the repository at this point in the history
[no important files changed]
  • Loading branch information
tomasnorre authored Nov 7, 2024
1 parent 425903c commit 2e55e9b
Show file tree
Hide file tree
Showing 3 changed files with 122 additions and 98 deletions.
108 changes: 56 additions & 52 deletions exercises/practice/affine-cipher/.docs/instructions.md
Original file line number Diff line number Diff line change
@@ -1,70 +1,74 @@
# Instructions

Create an implementation of the affine cipher,
an ancient encryption system created in the Middle East.
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.
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:

`E(x) = (ax + b) mod m`
- where `x` is the letter's index from 0 - length of alphabet - 1
- `m` is the length of the alphabet. For the roman alphabet `m == 26`.
- and `a` and `b` make the key
```text
E(x) = (ai + b) mod m
```

The decryption function is:
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.

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

To find the MMI of `a`:
The decryption function is:

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

`an mod m = 1`
- where `n` is the modular multiplicative inverse of `a mod m`
Where:

More information regarding how to find a Modular Multiplicative Inverse
and what it means can be found [here.](https://en.wikipedia.org/wiki/Modular_multiplicative_inverse)
- `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.

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 MMI of `a` is `x` such that the remainder after dividing `ax` by `m` is `1`:

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.
```text
ax mod m = 1
```

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.
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

- Encoding `test` gives `ybty` with the key a=5 b=7
- Decoding `ybty` gives `test` with the key a=5 b=7
- Decoding `ybty` gives `lqul` with the wrong key a=11 b=7
- Decoding `kqlfd jzvgy tpaet icdhm rtwly kqlon ubstx`
- gives `thequickbrownfoxjumpsoverthelazydog` with the key a=19 b=13
- Encoding `test` with the key a=18 b=13
- gives `Error: a and m must be coprime.`
- because a and m are not relatively prime

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

- simple example:
- `9 mod 26 = 9`
- `9 * 3 mod 26 = 27 mod 26 = 1`
- `3` is the MMI of `9 mod 26`
- a more complicated example:
- `15 mod 26 = 15`
- `15 * 7 mod 26 = 105 mod 26 = 1`
- `7` is the MMI of `15 mod 26`
- 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
22 changes: 0 additions & 22 deletions exercises/practice/affine-cipher/.meta/example.php
Original file line number Diff line number Diff line change
@@ -1,27 +1,5 @@
<?php

/*
* By adding type hints and enabling strict type checking, code can become
* easier to read, self-documenting and reduce the number of potential bugs.
* By default, type declarations are non-strict, which means they will attempt
* to change the original type to match the type specified by the
* type-declaration.
*
* In other words, if you pass a string to a function requiring a float,
* it will attempt to convert the string value to a float.
*
* To enable strict mode, a single declare directive must be placed at the top
* of the file.
* This means that the strictness of typing is configured on a per-file basis.
* This directive not only affects the type declarations of parameters, but also
* a function's return type.
*
* For more info review the Concept on strict type checking in the PHP track
* <link>.
*
* To disable strict typing, comment out the directive below.
*/

declare(strict_types=1);

function encode($text, $a, $b)
Expand Down
90 changes: 66 additions & 24 deletions exercises/practice/affine-cipher/AffineCipherTest.php
Original file line number Diff line number Diff line change
@@ -1,27 +1,5 @@
<?php

/*
* By adding type hints and enabling strict type checking, code can become
* easier to read, self-documenting and reduce the number of potential bugs.
* By default, type declarations are non-strict, which means they will attempt
* to change the original type to match the type specified by the
* type-declaration.
*
* In other words, if you pass a string to a function requiring a float,
* it will attempt to convert the string value to a float.
*
* To enable strict mode, a single declare directive must be placed at the top
* of the file.
* This means that the strictness of typing is configured on a per-file basis.
* This directive not only affects the type declarations of parameters, but also
* a function's return type.
*
* For more info review the Concept on strict type checking in the PHP track
* <link>.
*
* To disable strict typing, comment out the directive below.
*/

declare(strict_types=1);

/**
Expand All @@ -38,34 +16,58 @@ public static function setUpBeforeClass(): void
}

/**
* Tests for encoding English to ciphertext with keys.
* Encoding from English to affine cipher
*/

/**
* uuid 2ee1d9af-1c43-416c-b41b-cefd7d4d2b2a
* @testdox encode yes
*/
public function testEncodeYes(): void
{
$this->assertEquals('xbt', encode('yes', 5, 7));
}

/**
* uuid 785bade9-e98b-4d4f-a5b0-087ba3d7de4b
* @testdox encode no
*/
public function testEncodeNo(): void
{
$this->assertEquals('fu', encode('no', 15, 18));
}

/**
* uuid 2854851c-48fb-40d8-9bf6-8f192ed25054
* @testdox encode OMG
*/
public function testEncodeOMG(): void
{
$this->assertEquals('lvz', encode('OMG', 21, 3));
}

/**
* uuid bc0c1244-b544-49dd-9777-13a770be1bad
* @testdox encode O M G
*/
public function testEncodeOMGWithSpaces(): void
{
$this->assertEquals('hjp', encode('O M G', 25, 47));
}

/**
* uuid 381a1a20-b74a-46ce-9277-3778625c9e27
* @testdox encode mindblowingly
*/
public function testEncodemindblowingly(): void
{
$this->assertEquals('rzcwa gnxzc dgt', encode('mindblowingly', 11, 15));
}

/**
* uuid 6686f4e2-753b-47d4-9715-876fdc59029d
* @testdox encode numbers
*/
public function testEncodenumbers(): void
{
$this->assertEquals(
Expand All @@ -74,11 +76,19 @@ public function testEncodenumbers(): void
);
}

/**
* uuid ae23d5bd-30a8-44b6-afbe-23c8c0c7faa3
* @testdox encode deep thought
*/
public function testEncodeDeepThought(): void
{
$this->assertEquals('iynia fdqfb ifje', encode('Truth is fiction.', 5, 17));
}

/**
* uuid c93a8a4d-426c-42ef-9610-76ded6f7ef57
* @testdox encode all the letters
*/
public function testEncodeAllTheLetters(): void
{
$this->assertEquals(
Expand All @@ -87,21 +97,33 @@ public function testEncodeAllTheLetters(): void
);
}

/**
* uuid 0673638a-4375-40bd-871c-fb6a2c28effb
* @testdox encode with a not coprime to m
*/
public function testEncodeWithANotCoprimeToM(): void
{
$this->expectException(Exception::class);
encode('This is a test', 6, 17);
}

/**
* Test decoding from ciphertext to English with keys
* Decoding from affine cipher to all-lowercase-mashed-together English
*/

/**
* uuid 3f0ac7e2-ec0e-4a79-949e-95e414953438
* @testdox decode exercism
*/
public function testDecodeExercism(): void
{
$this->assertEquals('exercism', decode('tytgn fjr', 3, 7));
}

/**
* uuid 241ee64d-5a47-4092-a5d7-7939d259e077
* @testdox decode a sentence
*/
public function testDecodeASentence(): void
{
$this->assertEquals(
Expand All @@ -110,6 +132,10 @@ public function testDecodeASentence(): void
);
}

/**
* uuid 33fb16a1-765a-496f-907f-12e644837f5e
* @testdox decode numbers
*/
public function testDecodeNumbers(): void
{
$this->assertEquals(
Expand All @@ -118,6 +144,10 @@ public function testDecodeNumbers(): void
);
}

/**
* uuid 20bc9dce-c5ec-4db6-a3f1-845c776bcbf7
* @testdox decode all the letters
*/
public function testDecodeAllTheLetters(): void
{
$this->assertEquals(
Expand All @@ -126,6 +156,10 @@ public function testDecodeAllTheLetters(): void
);
}

/**
* uuid 623e78c0-922d-49c5-8702-227a3e8eaf81
* @testdox decode with no spaces in input
*/
public function testDecodeWithNoSpacesInInput(): void
{
$this->assertEquals(
Expand All @@ -134,6 +168,10 @@ public function testDecodeWithNoSpacesInInput(): void
);
}

/**
* uuid 58fd5c2a-1fd9-4563-a80a-71cff200f26f
* @testdox decode with too many spaces
*/
public function testDecodeWithTooManySpaces(): void
{
$this->assertEquals(
Expand All @@ -142,6 +180,10 @@ public function testDecodeWithTooManySpaces(): void
);
}

/**
* uuid b004626f-c186-4af9-a3f4-58f74cdb86d5
* @testdox decode with a not coprime to m
*/
public function testDecodeWithANotCoprimeToM(): void
{
$this->expectException(Exception::class);
Expand Down

0 comments on commit 2e55e9b

Please sign in to comment.