/ assign4 / DecryptCaesarCore.java
DecryptCaesarCore.java
 1  /// Caesar cipher decoder - core executable and embeddable class
 2  ///
 3  /// SPDX-License-Identifier: GPL-3.0-or-later
 4  /// SPDX-FileCopyrightText: 2024 Jonas Smedegaard <dr@jones.dk>
 5  ///
 6  /// Decrypts a string encoded with the Caesar cipher.
 7  /// The encrypted string is passed as first command-line argument,
 8  /// and all possible decryptions are emitted to stdout.
 9  ///
10  /// Core class usable as self-contained executable via method main()
11  /// and also embedded in a larger system by instantiating GridCore().
12  ///
13  /// @version 0.0.1
14  /// @see <https://app.radicle.xyz/nodes/ash.radicle.garden/rad:z3YzABgyz2D36LiKe3YcdJ6PcDCXM/tree/assign4/README.md>
15  /// @see <https://en.wikipedia.org/wiki/Caesar_cipher>
16  /// @see <https://moodle.ruc.dk/mod/assign/view.php?id=507318>
17  public class DecryptCaesarCore {
18  
19  	/// Constructs a new DecryptCaesar object.
20  	///
21  	/// This allows code reuse in more ergonomic wrapper
22  	///
23  	/// @param args  ciphertext, alphabet and key as first arguments
24  	public DecryptCaesarCore(String[] args) {
25  		ciphertext = args[0];
26  		alphabet = args[1];
27  		knownKey = Integer.parseInt(args[2]);
28  	}
29  
30  	/// main method for the CLI tool
31  	///
32  	/// @param args  ciphertext as first argument
33  	public static void main(String[] args) {
34  		alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
35  		ciphertext = args[0];
36  
37  		decipherAsNeeded();
38  	}
39  
40  	static String alphabet, ciphertext;
41  	static int knownKey;
42  
43  	/// Decode ciphertext, by brute force or once if key is known
44  	public static void decipherAsNeeded() {
45  		if (knownKey > 0) {
46  			decipher(knownKey);
47  		} else {
48  			for ( int i = 0; i < alphabet.length(); i++) {
49  				decipher(i);
50  			}
51  		}
52  	}
53  
54  	/// Decode a ciphertext
55  	public static void decipher(int key) {
56  		// compose a plaintext iterating over each ciphertext character
57  		final int space = alphabet.length();
58  		String plaintext = "";
59  		for ( int j = 0; j < ciphertext.length(); j++) {
60  
61  			// extract character, and look it up in alphabet
62  			char c = ciphertext.charAt(j);
63  			int k = alphabet.indexOf(c);
64  
65  			// return alien character as-is,
66  			// or if found return rotated position, modulo the space
67  			plaintext += (k < 0) ? c : alphabet.charAt((key + k) % space);
68  		}
69  		System.out.printf("%s: %s%n", key, plaintext);
70  	}
71  }