i did caesar cipher code by java it runs but doesnt encrypt anything after user enter the key !
here is my code
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();
}
}
run:
Enter The Plain Text:
Reem LA
Enter The Key:
2
The Cipher Text
This is probably the easiest way to do it and the most easy to understand:
Try this:
This will work for all alphabetical strings... But as per your program, this will convert the original message to lowercase. So this is not pure encryption since your program is case insensitive.
If you want your program to be case sensitive, here is the program:
Hope this gives some idea. All the best.
Using
indexOf
is not very efficient... You can do integer arithmetic onchar
values to get their indices.I included comments in the code to explain more, but this is what I came up with.
The output should be something like