-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCaesarCipher.java
More file actions
73 lines (62 loc) · 2.97 KB
/
Copy pathCaesarCipher.java
File metadata and controls
73 lines (62 loc) · 2.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import java.util.Scanner;
// Caesar Cipher program that encrypts and decrypts text
public class CaesarCipher {
// Stores the result of the encryption or decryption
public static StringBuilder result = new StringBuilder();
// Encrypts text using a Caesar Cipher with the given shift key
public static String encrypt(String text, int shift) {
for (char character : text.toCharArray()) { // Loops through each character in the text
if (Character.isLetter(character)) { // Checks if the character is a letter
char base = Character.isLowerCase(character) ? 'a' : 'A'; // Checks if the character is lowercase or uppercase and sets the base
char shifted = (char) ((character - base + shift) % 26 + base); // Shift calculation
result.append(shifted); // Adds the shifted character to the result
}
else {
result.append(character); // If the character is not a letter then keep it the same
}
}
return result.toString(); // Returns the result as a string
}
// Decrypts text using a Caesar Cipher with the given shift key
public static String decrypt(String text, int shift) {
for (char character : text.toCharArray()) {
if (Character.isLetter(character)) {
char base = Character.isLowerCase(character) ? 'a' : 'A';
char unshifted = (char) ((character - shift - base + 26) % 26 + base); // Unshift calculation
result.append(unshifted);
}
else {
result.append(character);
}
}
return result.toString();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Would you like to encrypt or decrypt text? (E/D): ");
String choice = scanner.nextLine();
// Encrypt
if (choice.equalsIgnoreCase("E")) {
System.out.print("Enter text to encrypt: ");
String inputText = scanner.nextLine();
System.out.print("Enter shift key (0-25): ");
int shiftKey = scanner.nextInt();
String encrypted = encrypt(inputText, shiftKey);
System.out.println("Encrypted text: " + encrypted);
}
// Decrypt
else if (choice.equalsIgnoreCase("D")) {
System.out.print("Enter text to decrypt: ");
String inputText = scanner.nextLine();
System.out.print("Enter shift key (0-25): ");
int shiftKey = scanner.nextInt();
String decrypted = decrypt(inputText, shiftKey);
System.out.println("Decrypted text: " + decrypted);
}
// Invalid input (ends the program)
else {
System.out.println("Invalid input");
}
scanner.close();
}
}