MCPcopy Create free account
hub / github.com/TheAlgorithms/Java / AffineCipher

Class AffineCipher

src/main/java/com/thealgorithms/ciphers/AffineCipher.java:21–87  ·  view source on GitHub ↗

The AffineCipher class implements the Affine cipher, a type of monoalphabetic substitution cipher. It encrypts and decrypts messages using a linear transformation defined by the formula: E(x) = (a x + b) mod m D(y) = a^-1 (y - b) mod m where: - E(x) is the encrypted character, - D(y) is th

Source from the content-addressed store, hash-verified

19 * The class provides methods for encrypting and decrypting messages, as well as a main method to demonstrate its usage.
20 */
21final class AffineCipher {
22 private AffineCipher() {
23 }
24
25 // Key values of a and b
26 static int a = 17;
27 static int b = 20;
28
29 /**
30 * Encrypts a message using the Affine cipher.
31 *
32 * @param msg the plaintext message as a character array
33 * @return the encrypted ciphertext
34 */
35 static String encryptMessage(char[] msg) {
36 // Cipher Text initially empty
37 StringBuilder cipher = new StringBuilder();
38 for (int i = 0; i < msg.length; i++) {
39 // Avoid space to be encrypted
40 /* applying encryption formula ( a * x + b ) mod m
41 {here x is msg[i] and m is 26} and added 'A' to
42 bring it in the range of ASCII alphabet [65-90 | A-Z] */
43 if (msg[i] != ' ') {
44 cipher.append((char) ((((a * (msg[i] - 'A')) + b) % 26) + 'A'));
45 } else { // else simply append space character
46 cipher.append(msg[i]);
47 }
48 }
49 return cipher.toString();
50 }
51
52 /**
53 * Decrypts a ciphertext using the Affine cipher.
54 *
55 * @param cipher the ciphertext to decrypt
56 * @return the decrypted plaintext message
57 */
58 static String decryptCipher(String cipher) {
59 StringBuilder msg = new StringBuilder();
60 int aInv = 0;
61 int flag;
62
63 // Find a^-1 (the multiplicative inverse of a in the group of integers modulo m.)
64 for (int i = 0; i < 26; i++) {
65 flag = (a * i) % 26;
66
67 // Check if (a * i) % 26 == 1,
68 // then i will be the multiplicative inverse of a
69 if (flag == 1) {
70 aInv = i;
71 break;
72 }
73 }
74 for (int i = 0; i < cipher.length(); i++) {
75 /* Applying decryption formula a^-1 * (x - b) mod m
76 {here x is cipher[i] and m is 26} and added 'A'
77 to bring it in the range of ASCII alphabet [65-90 | A-Z] */
78 if (cipher.charAt(i) != ' ') {

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected