Skip to content

Commit 2c26c13

Browse files
add Caesar cipher
1 parent 76ac7ce commit 2c26c13

2 files changed

Lines changed: 68 additions & 0 deletions

File tree

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package com.examplehub.ciphers;
2+
3+
/**
4+
* https://en.wikipedia.org/wiki/Caesar_cipher
5+
*/
6+
public class CaesarCipher {
7+
8+
/**
9+
* Encrypt a string by caesar cipher algorithm.
10+
*
11+
* @param origin the origin text.
12+
* @param steps the steps to be moved.
13+
* @return the string encrypted.
14+
*/
15+
public static String encrypt(String origin, int steps) {
16+
char[] password = origin.toCharArray();
17+
for (int i = 0; i < password.length; ++i) {
18+
if (Character.isUpperCase(password[i])) {
19+
password[i] = (char) ('A' + (password[i] - 'A' + steps) % 26);
20+
} else if (Character.isLowerCase(password[i])) {
21+
password[i] = (char) ('a' + (password[i] - 'a' + steps) % 26);
22+
}
23+
}
24+
return String.valueOf(password);
25+
}
26+
27+
/**
28+
* Decrypt a string.
29+
*
30+
* @param password the password to be decrypted.
31+
* @param steps the steps to be moved.
32+
* @return the string decrypted.
33+
*/
34+
public static String decrypt(String password, int steps) {
35+
char[] origin = password.toCharArray();
36+
for (int i = 0; i < password.length(); ++i) {
37+
if (Character.isUpperCase(origin[i])) {
38+
origin[i] = (char) ('A' + (origin[i] - 'A' - steps + 26) % 26);
39+
} else if (Character.isLowerCase(origin[i])) {
40+
origin[i] = (char) ('a' + (origin[i] - 'a' - steps + 26) % 26);
41+
}
42+
}
43+
return String.valueOf(origin);
44+
}
45+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.examplehub.ciphers;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
import static org.junit.jupiter.api.Assertions.*;
6+
7+
class CaesarCipherTest {
8+
@Test
9+
void testEncrypt() {
10+
assertEquals("DEFGHIJKLMNOPQRSTUVWXYZABC",
11+
CaesarCipher.encrypt("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 3));
12+
assertEquals("defghijklmnopqrstuvwxyzabc",
13+
CaesarCipher.encrypt("abcdefghijklmnopqrstuvwxyz", 3));
14+
}
15+
16+
@Test
17+
void testDecrypt() {
18+
assertEquals("ABCDEFGHIJKLMNOPQRSTUVWXYZ",
19+
CaesarCipher.decrypt("DEFGHIJKLMNOPQRSTUVWXYZABC", 3));
20+
assertEquals("abcdefghijklmnopqrstuvwxyz",
21+
CaesarCipher.decrypt("defghijklmnopqrstuvwxyzabc", 3));
22+
}
23+
}

0 commit comments

Comments
 (0)