-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCaesar Cipher.java
40 lines (29 loc) · 1009 Bytes
/
Caesar Cipher.java
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
public class Main
{
public static String encrypt(String message, int key)
{
String cipher = "";
char newCharacter;
int asciiValue;
for (int i = 0; i < message.length(); i++)
{
asciiValue = (((message.charAt(i) + key) - 97) % 26) + 97;
newCharacter = (char)asciiValue;
cipher = cipher + newCharacter;
}
return cipher;
}
public static String decrypt(String codedMessage, int key)
{
return encrypt(codedMessage, 26 - key);
}
public static void main(String args[])
{
String text = "byeworld"; //lowercase text
int k = 3;
System.out.println("Original text is '" + text + "'\n");
String encryptedMessage = encrypt(text, k);
System.out.println("Encoded message: " + encryptedMessage);
System.out.println("Decoded message: " + decrypt(encryptedMessage, k));
}
}