-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEncrypting Caesar Cipher
69 lines (56 loc) · 2.34 KB
/
Encrypting Caesar Cipher
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
import edu.duke.*;
public class CaesarCipher
{
public String encrypt(String input, int key)
{
//Make a StringBuilder with message (encrypted)
StringBuilder encrypted = new StringBuilder(input);
//Write down the alphabet
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
//Compute the shifted alphabet
String shiftedAlphabet = alphabet.substring(key)+
alphabet.substring(0,key);
String alphabet2=alphabet.toLowerCase();
String shiftedAlphabet2=alphabet2.substring(key)+
alphabet2.substring(0,key);
char currChar;
//Count from 0 to < length of encrypted, (call it i)
for(int i = 0; i < encrypted.length(); i++) {
//Look at the ith character of encrypted (call it currChar)
currChar = encrypted.charAt(i);
if(Character.isUpperCase(currChar)){
//Find the index of currChar in the alphabet (call it idx)
int idx = alphabet.indexOf(currChar);
//If currChar is in the alphabet
if(idx != -1){
//Get the idxth character of shiftedAlphabet (newChar)
char newChar = shiftedAlphabet.charAt(idx);
//Replace the ith character of encrypted with newChar
encrypted.setCharAt(i, newChar);
}
//Otherwise: do nothing
}
if(Character.isLowerCase(currChar)){
int idx = alphabet2.indexOf(currChar);
//If currChar is in the alphabet
if(idx != -1){
//Get the idxth character of shiftedAlphabet (newChar)
char newChar = shiftedAlphabet2.charAt(idx);
//Replace the ith character of encrypted with newChar
encrypted.setCharAt(i, newChar);
}
}
}
//Your answer is the String inside of encrypted
return encrypted.toString();
}
public void testCaesar() {
int key = 3;
FileResource fr = new FileResource();
String message = fr.asString();
String encrypted = encrypt(message, key);
System.out.println(encrypted);
String decrypted = encrypt(encrypted, 26-key);
System.out.println(decrypted);
}
}