ðŸŽ‰ Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io ðŸŽ‰

# Kershoc's solution

## to Affine Cipher in the PHP Track

Published at Jul 21 2020 · 0 comments
Instructions
Test suite
Solution

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`

• 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

the decryption function is:

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

To find the MMI of `a`:

`an mod m = 1`

• where `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.

## 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`

### affine-cipher_test.php

``````<?php

/**
* The test are divided into two groups:
*
* * Encoding from English to affine cipher,
* * Decoding from affine cipher to all-lowercase-mashed-together English
*/
class AffineCipherTest extends PHPUnit\Framework\TestCase
{
public static function setUpBeforeClass() : void
{
require_once 'affine-cipher.php';
}

/**
* Tests for encoding English to ciphertext with keys.
*/

public function testEncodeYes() : void
{
\$this->assertEquals('xbt', encode('yes', 5, 7));
}

public function testEncodeNo() : void
{
\$this->assertEquals('fu', encode('no', 15, 18));
}

public function testEncodeOMG() : void
{
\$this->assertEquals('lvz', encode('OMG', 21, 3));
}

public function testEncodeOMGWithSpaces() : void
{
\$this->assertEquals('hjp', encode('O M G', 25, 47));
}

public function testEncodemindblowingly() : void
{
\$this->assertEquals('rzcwa gnxzc dgt', encode('mindblowingly', 11, 15));
}

public function testEncodenumbers() : void
{
\$this->assertEquals(
'jqgjc rw123 jqgjc rw',
encode('Testing,1 2 3, testing.', 3, 4)
);
}

public function testEncodeDeepThought() : void
{
\$this->assertEquals('iynia fdqfb ifje', encode('Truth is fiction.', 5, 17));
}

public function testEncodeAllTheLetters() : void
{
\$this->assertEquals(
'swxtj npvyk lruol iejdc blaxk swxmh qzglf',
encode('The quick brown fox jumps over the lazy dog.', 17, 33)
);
}

public function testEncodeWithANotCoprimeToM() : void
{
\$this->expectException(Exception::class);
encode('This is a test', 6, 17);
}

/**
* Test decoding from ciphertext to English with keys
*/

public function testDecodeExercism() : void
{
\$this->assertEquals('exercism', decode('tytgn fjr', 3, 7));
}

public function testDecodeASentence() : void
{
\$this->assertEquals(
decode("qdwju nqcro muwhn odqun oppmd aunwd o", 19, 16),
"anobstacleisoftenasteppingstone"
);
}

public function testDecodeNumbers() : void
{
\$this->assertEquals(
decode("odpoz ub123 odpoz ub", 25, 7),
"testing123testing"
);
}

public function testDecodeAllTheLetters() : void
{
\$this->assertEquals(
decode("swxtj npvyk lruol iejdc blaxk swxmh qzglf", 17, 33),
"thequickbrownfoxjumpsoverthelazydog"
);
}

public function testDecodeWithNoSpacesInInput() : void
{
\$this->assertEquals(
decode("swxtjnpvyklruoliejdcblaxkswxmhqzglf", 17, 33),
"thequickbrownfoxjumpsoverthelazydog"
);
}

public function testDecodeWithTooManySpaces() : void
{
\$this->assertEquals(
decode("vszzm    cly   yd cg    qdp", 15, 16),
"jollygreengiant"
);
}

public function testDecodeWithANotCoprimeToM() : void
{
\$this->expectException(Exception::class);
decode("Test", 13, 5);
}
}``````
``````<?php
declare(strict_types=1);

define('ALPHABET', range('a','z'));
define('CYPHER', array_flip(ALPHABET));
define('ALPHABET_LENGTH', count(ALPHABET));

// E(x) = (ax + b) mod m
function encode(string \$text, int \$akey, int \$bkey): string
{
if (!isCoPrime(\$akey, ALPHABET_LENGTH)) {
throw new Exception("Error: a and m must be coprime.");
}
\$text = mb_strtolower(\$text);

\$out = '';
foreach(mb_str_split(\$text) as \$char) {
if (array_key_exists(\$char,CYPHER)) {
\$key = (\$akey*CYPHER[\$char] + \$bkey) % ALPHABET_LENGTH;
\$out .= ALPHABET[\$key];
}
if (ctype_digit(\$char)) {
\$out .= \$char;
}
}
return trim(chunk_split(\$out, 5, ' '));
}

// D(y) = a^-1(y - b) mod m
function decode(string \$text, int \$akey, int \$bkey): string
{
if (!isCoPrime(\$akey, ALPHABET_LENGTH)) {
throw new Exception("Error: a and m must be coprime.");
}
\$mmi = gmp_intval(gmp_invert(\$akey, ALPHABET_LENGTH));
\$text = mb_strtolower(\$text);

\$out = '';
foreach(mb_str_split(\$text) as \$char) {
if (array_key_exists(\$char,CYPHER)) {
\$key = \$mmi * (CYPHER[\$char] - \$bkey) % ALPHABET_LENGTH;
while(\$key < 0) {
\$key += ALPHABET_LENGTH;
}
\$out .= ALPHABET[\$key];
}
if (ctype_digit(\$char)) {
\$out .= \$char;
}
}
return \$out;
}

function isCoPrime(\$a, \$b): bool
{
return gmp_intval(gmp_gcd(\$a, \$b)) === 1;
}``````