Home > Blockchain >  Ceasar Cipher Encryption and Decryption with Java
Ceasar Cipher Encryption and Decryption with Java

Time:04-07

I'm use Ceaser’s cipher (shifting the alphabet by a shift pattern) with the shift pattern of two and then encrypt a sentence to print it on screen. Then I'm trying to store the encrypted message in a different string and decrypt it back to the original string. I've tried the following code below so far but I can't get it to decrypt back. Basically trying to encrypt and then decrypt in Ceasar's cipher, but so far I can only encrypt and not decrypt it back. Any suggestions are appreciated!

public class Solution { //to keep track of index
  public static final String alpha = "abcdefghijklmnopqrstuvwxyz";

  public static String encrypt(String message, int shiftKey) {
    message = message.toLowerCase();
    String cipherText = "";
    for (int ii = 0; ii < message.length(); ii  ) {
      int charPosition = alpha.indexOf(message.charAt(ii));
      int keyVal = (shiftKey   charPosition) % 26;
      char replaceVal = alpha.charAt(keyVal);
      cipherText  = replaceVal;
    }
    return cipherText;
  }

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String message = new String();
    int key = 0;
    System.out.print("Enter the String for Encryption:");
    message = sc.next();

    System.out.println("\n\nEnter Shift Key:");
    key = sc.nextInt();
    System.out.println("\nEncrpyted msg:"   encrypt(message, key));
  } //main method ends

CodePudding user response:

Right, so can you store the cryptogram in a String, then call your encrypt method with that string and -1 * key?

CodePudding user response:

If you encrypt with shiftKey = 10 you need to decrypt with shiftKey = 16. So when you enter -10 to reverse the process, you need to add 26 if it is negative. Right before your for(ii ..) loop put this.

 shiftKey = shiftKey < 0 ? alpha.length() shiftKey : shiftKey;

Says if shiftKey is less than 0, add alpha.length() to it. Otherwise keep it as is.

  • Related