Skip to content

Commit 39c8aef

Browse files
lemoncurryFridaTveit
authored andcommitted
affine-cipher: Add new exercise (exercism#1600)
* affine-cipher: Add new exercise * Change settings.gradle * affine-cipher: Add exercise * affine-cipher: add version file * affine-cipher: fix method name * fix test * fix mode * fix test name and style
1 parent 22526c2 commit 39c8aef

9 files changed

Lines changed: 331 additions & 0 deletions

File tree

‎config.json‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -949,6 +949,19 @@
949949
"strings"
950950
]
951951
},
952+
{
953+
"slug": "affine-cipher",
954+
"uuid": "e6e3faaf-54c2-4782-93af-bb8d95403f2a",
955+
"core": false,
956+
"unlocked_by": "rotational-cipher",
957+
"difficulty": 6,
958+
"topics": [
959+
"cryptography",
960+
"security",
961+
"strings",
962+
"text_formatting"
963+
]
964+
},
952965
{
953966
"slug": "two-bucket",
954967
"uuid": "210bf628-b385-443b-8329-3483cc6e8d7e",
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Please notice that the `%` operator is not equivalent to the one described in the problem description
2+
([see Wikipedia entry for Modulo operation](https://en.wikipedia.org/wiki/Modulo_operation)).
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
import java.util.ArrayList;
2+
import java.util.List;
3+
4+
class AffineCipher {
5+
private static final int GROUP_SIZE = 5;
6+
private static final int ALPHABET_SIZE = 26;
7+
private static final int ALPHABET_START_UNICODE = 97;
8+
9+
private enum Mode {
10+
ENCODE,
11+
DECODE
12+
}
13+
14+
String encode(String plainMessage, int keyA, int keyB) {
15+
return splitIntoFiveLetterWords(
16+
translate(plainMessage, keyA, keyB, Mode.ENCODE));
17+
}
18+
19+
String decode(String cipheredMessage, int keyA, int keyB) {
20+
return translate(cipheredMessage, keyA, keyB, Mode.DECODE);
21+
}
22+
23+
private static int modInverse(int keyA) {
24+
int keyAMod = Math.floorMod(keyA, ALPHABET_SIZE);
25+
for (int n = 1; n < ALPHABET_SIZE; n++) {
26+
if (Math.floorMod(keyAMod * n, ALPHABET_SIZE) == 1) {
27+
return n;
28+
}
29+
}
30+
return 1;
31+
}
32+
33+
private static String splitIntoFiveLetterWords(String text) {
34+
List<String> words = new ArrayList<>();
35+
36+
for (int i = 0; i < text.length(); i += GROUP_SIZE) {
37+
words.add(text.substring(i, Math.min(text.length(), i + GROUP_SIZE)));
38+
}
39+
40+
return String.join(" ", words);
41+
}
42+
43+
private static String translate(String text, int keyA, int keyB, Mode mode) {
44+
int inv = modInverse(keyA);
45+
if (inv == 1) {
46+
throw new IllegalArgumentException("Error: keyA and alphabet size must be coprime.");
47+
}
48+
49+
StringBuilder stringBuilder = new StringBuilder();
50+
51+
text.chars()
52+
.filter(Character::isLetterOrDigit)
53+
.map(Character::toLowerCase)
54+
.forEach(c -> {
55+
int orig = c - ALPHABET_START_UNICODE;
56+
if (orig < 0) {
57+
stringBuilder.appendCodePoint(c);
58+
} else {
59+
if (mode == Mode.ENCODE) {
60+
stringBuilder.appendCodePoint(
61+
ALPHABET_START_UNICODE + Math.floorMod(keyA * orig + keyB, ALPHABET_SIZE)
62+
);
63+
} else if (mode == Mode.DECODE) {
64+
stringBuilder.appendCodePoint(
65+
ALPHABET_START_UNICODE + Math.floorMod(inv * (orig - keyB), ALPHABET_SIZE)
66+
);
67+
}
68+
}
69+
});
70+
71+
return stringBuilder.toString();
72+
}
73+
74+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
2.0.0

‎exercises/affine-cipher/README.md‎

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
# Affine Cipher
2+
3+
Create an implementation of the affine cipher,
4+
an ancient encryption system created in the Middle East.
5+
6+
The affine cipher is a type of monoalphabetic substitution cipher.
7+
Each character is mapped to its numeric equivalent, encrypted with
8+
a mathematical function and then converted to the letter relating to
9+
its new numeric value. Although all monoalphabetic ciphers are weak,
10+
the affine cypher is much stronger than the atbash cipher,
11+
because it has many more keys.
12+
13+
the encryption function is:
14+
15+
`E(x) = (ax + b) mod m`
16+
- where `x` is the letter's index from 0 - length of alphabet - 1
17+
- `m` is the length of the alphabet. For the roman alphabet `m == 26`.
18+
- and `a` and `b` make the key
19+
20+
the decryption function is:
21+
22+
`D(y) = a^-1(y - b) mod m`
23+
- where `y` is the numeric value of an encrypted letter, ie. `y = E(x)`
24+
- it is important to note that `a^-1` is the modular multiplicative inverse
25+
of `a mod m`
26+
- the modular multiplicative inverse of `a` only exists if `a` and `m` are
27+
coprime.
28+
29+
To find the MMI of `a`:
30+
31+
`an mod m = 1`
32+
- where `n` is the modular multiplicative inverse of `a mod m`
33+
34+
More information regarding how to find a Modular Multiplicative Inverse
35+
and what it means can be found [here.](https://en.wikipedia.org/wiki/Modular_multiplicative_inverse)
36+
37+
Because automatic decryption fails if `a` is not coprime to `m` your
38+
program should return status 1 and `"Error: a and m must be coprime."`
39+
if they are not. Otherwise it should encode or decode with the
40+
provided key.
41+
42+
The Caesar (shift) cipher is a simple affine cipher where `a` is 1 and
43+
`b` as the magnitude results in a static displacement of the letters.
44+
This is much less secure than a full implementation of the affine cipher.
45+
46+
Ciphertext is written out in groups of fixed length, the traditional group
47+
size being 5 letters, and punctuation is excluded. This is to make it
48+
harder to guess things based on word boundaries.
49+
50+
## Examples
51+
52+
- Encoding `test` gives `ybty` with the key a=5 b=7
53+
- Decoding `ybty` gives `test` with the key a=5 b=7
54+
- Decoding `ybty` gives `lqul` with the wrong key a=11 b=7
55+
- Decoding `kqlfd jzvgy tpaet icdhm rtwly kqlon ubstx`
56+
- gives `thequickbrownfoxjumpsoverthelazydog` with the key a=19 b=13
57+
- Encoding `test` with the key a=18 b=13
58+
- gives `Error: a and m must be coprime.`
59+
- because a and m are not relatively prime
60+
61+
### Examples of finding a Modular Multiplicative Inverse (MMI)
62+
63+
- simple example:
64+
- `9 mod 26 = 9`
65+
- `9 * 3 mod 26 = 27 mod 26 = 1`
66+
- `3` is the MMI of `9 mod 26`
67+
- a more complicated example:
68+
- `15 mod 26 = 15`
69+
- `15 * 7 mod 26 = 105 mod 26 = 1`
70+
- `7` is the MMI of `15 mod 26`
71+
72+
# Java Tips
73+
74+
Please notice that the `%` operator is not equivalent to the one described in the problem description
75+
([see Wikipedia entry for Modulo operation](https://en.wikipedia.org/wiki/Modulo_operation)).
76+
77+
# Running the tests
78+
79+
You can run all the tests for an exercise by entering
80+
81+
```sh
82+
$ gradle test
83+
```
84+
85+
in your terminal.
86+
87+
## Source
88+
89+
Wikipedia [http://en.wikipedia.org/wiki/Affine_cipher](http://en.wikipedia.org/wiki/Affine_cipher)
90+
91+
## Submitting Incomplete Solutions
92+
93+
It's possible to submit an incomplete solution so you can see how others have completed the exercise.
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
apply plugin: "java"
2+
apply plugin: "eclipse"
3+
apply plugin: "idea"
4+
5+
repositories {
6+
mavenCentral()
7+
}
8+
9+
dependencies {
10+
testCompile "junit:junit:4.12"
11+
}
12+
13+
test {
14+
testLogging {
15+
exceptionFormat = 'full'
16+
events = ["passed", "failed", "skipped"]
17+
}
18+
}

‎exercises/affine-cipher/src/main/java/.keep‎

Whitespace-only changes.
Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
import org.junit.Before;
2+
import org.junit.Ignore;
3+
import org.junit.Rule;
4+
import org.junit.Test;
5+
import org.junit.rules.ExpectedException;
6+
7+
import static org.junit.Assert.assertEquals;
8+
9+
public class AffineCipherTest {
10+
11+
private AffineCipher affineCipher;
12+
13+
@Before
14+
public void genAffineCipher() {
15+
affineCipher = new AffineCipher();
16+
}
17+
18+
@Rule
19+
public ExpectedException expectedException = ExpectedException.none();
20+
21+
@Test
22+
public void testEncodeYes() {
23+
assertEquals("xbt", affineCipher.encode("yes", 5, 7));
24+
}
25+
26+
@Ignore("Remove to run test")
27+
@Test
28+
public void testEncodeNo() {
29+
assertEquals("fu", affineCipher.encode("no", 15, 18));
30+
}
31+
32+
33+
@Ignore("Remove to run test")
34+
@Test
35+
public void testEncodeOMG() {
36+
assertEquals("lvz", affineCipher.encode("OMG", 21, 3));
37+
}
38+
39+
@Ignore("Remove to run test")
40+
@Test
41+
public void testEncodeO_M_G() {
42+
assertEquals("hjp", affineCipher.encode("O M G", 25, 47));
43+
}
44+
45+
@Ignore("Remove to run test")
46+
@Test
47+
public void testEncodeMindBlowingly() {
48+
assertEquals("rzcwa gnxzc dgt", affineCipher.encode("mindblowingly", 11, 15));
49+
}
50+
51+
@Ignore("Remove to run test")
52+
@Test
53+
public void testEncodeNumbers() {
54+
assertEquals("jqgjc rw123 jqgjc rw",
55+
affineCipher.encode("Testing,1 2 3, testing.", 3, 4));
56+
}
57+
58+
@Ignore("Remove to run test")
59+
@Test
60+
public void testEncodeDeepThought() {
61+
assertEquals("iynia fdqfb ifje",
62+
affineCipher.encode("Truth is fiction.", 5, 17));
63+
}
64+
65+
@Ignore("Remove to run test")
66+
@Test
67+
public void testEncodeAllTheLetters() {
68+
assertEquals("swxtj npvyk lruol iejdc blaxk swxmh qzglf",
69+
affineCipher.encode("The quick brown fox jumps over the lazy dog.", 17, 33));
70+
}
71+
72+
@Ignore("Remove to run test")
73+
@Test
74+
public void testEncodeThrowsMeaningfulException() throws IllegalArgumentException {
75+
expectedException.expect(IllegalArgumentException.class);
76+
expectedException.expectMessage("Error: keyA and alphabet size must be coprime.");
77+
78+
affineCipher.encode("This is a test", 6, 17);
79+
}
80+
81+
@Ignore("Remove to run test")
82+
@Test
83+
public void testDecodeExercism() {
84+
assertEquals("exercism", affineCipher.decode("tytgn fjr", 3, 7));
85+
}
86+
87+
@Ignore("Remove to run test")
88+
@Test
89+
public void testDecodeSentence() {
90+
assertEquals("anobstacleisoftenasteppingstone",
91+
affineCipher.decode("qdwju nqcro muwhn odqun oppmd aunwd o", 19, 16));
92+
}
93+
94+
@Ignore("Remove to run test")
95+
@Test
96+
public void testDecodeNumbers() {
97+
assertEquals("testing123testing", affineCipher.decode("odpoz ub123 odpoz ub", 25, 7));
98+
}
99+
100+
@Ignore("Remove to run test")
101+
@Test
102+
public void testDecodeAllTheLetters() {
103+
assertEquals("thequickbrownfoxjumpsoverthelazydog",
104+
affineCipher.decode("swxtj npvyk lruol iejdc blaxk swxmh qzglf", 17, 33));
105+
}
106+
107+
@Ignore("Remove to run test")
108+
@Test
109+
public void testDecodeWithNoSpaces() {
110+
assertEquals("thequickbrownfoxjumpsoverthelazydog",
111+
affineCipher.decode("swxtjnpvyklruoliejdcblaxkswxmhqzglf", 17, 33));
112+
}
113+
114+
@Ignore("Remove to run test")
115+
@Test
116+
public void testDecodeWithTooManySpaces() {
117+
assertEquals("jollygreengiant", affineCipher.decode("vszzm cly yd cg qdp", 15, 16));
118+
}
119+
120+
@Ignore("Remove to run test")
121+
@Test
122+
public void testDecodeThrowsMeaningfulException() {
123+
expectedException.expect(IllegalArgumentException.class);
124+
expectedException.expectMessage("Error: keyA and alphabet size must be coprime.");
125+
126+
affineCipher.decode("Test", 13, 5);
127+
}
128+
129+
}

‎exercises/settings.gradle‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
include 'accumulate'
22
include 'acronym'
3+
include 'affine-cipher'
34
include 'all-your-base'
45
include 'allergies'
56
include 'alphametics'

0 commit comments

Comments
 (0)