Created
January 31, 2018 01:30
-
-
Save dsouzadyn/14efd3e9a0d6ae69a37ad3ad83a7d5e5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
public class CaesarCipher | |
{ | |
public static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz"; | |
public static String encrypt(String plainText, int shiftKey) | |
{ | |
plainText = plainText.toLowerCase(); | |
String cipherText = ""; | |
for (int i = 0; i < plainText.length(); i++) | |
{ | |
int charPosition = ALPHABET.indexOf(plainText.charAt(i)); | |
int keyVal = (shiftKey + charPosition) % 26; | |
char replaceVal = ALPHABET.charAt(keyVal); | |
cipherText += replaceVal; | |
} | |
return cipherText; | |
} | |
public static String decrypt(String cipherText, int shiftKey) | |
{ | |
cipherText = cipherText.toLowerCase(); | |
String plainText = ""; | |
for (int i = 0; i < cipherText.length(); i++) | |
{ | |
int charPosition = ALPHABET.indexOf(cipherText.charAt(i)); | |
int keyVal = (charPosition - shiftKey) % 26; | |
if (keyVal < 0) | |
{ | |
keyVal = ALPHABET.length() + keyVal; | |
} | |
char replaceVal = ALPHABET.charAt(keyVal); | |
plainText += replaceVal; | |
} | |
return plainText; | |
} | |
public static void main(String[] args) | |
{ | |
Scanner sc = new Scanner(System.in); | |
System.out.println("Enter the String for Encryption: "); | |
String message = new String(); | |
message = sc.next(); | |
System.out.println(encrypt(message, 3)); | |
System.out.println(decrypt(encrypt(message, 3), 3)); | |
sc.close(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment