如何在凯撒密码中使用 shifAlphabet 方法加密纯文本 (JAVA)

How to encrypt a plain text using shifAlphabet method in caesar cipher (JAVA)

这就是我所做的

我正在编写一个程序来加密文本。首先,我删除了空格、标点符号并将字符串转换为大写。然后我混淆了例如通过将 OB 添加到每个元音,使得 HEREISTHEMAN 将变为 HOBEOBISTHOBEMOBAN。然后我使用 +1 shift 键进行 caesarify,但没有返回 IPCFPCJTUIPCFNPCBO。它返回“BCDEFGHIJKLMNOPQRSTUVWXYZA。请提供任何帮助,以便我可以继续执行其余步骤。谢谢。

这是我的代码

import java.util.Scanner;
public class ProjectCrypto {
    static String text;
    public static void main(String[] args) {

        System.out.println(normalizeText());
        System.out.println(Obify());

        System.out.print("Enter shift: ");
        Scanner val = new Scanner(System.in);
        int key = val.nextInt();

        System.out.println(caesarify(Obify(), key));

    }

    public static String normalizeText(){
    Scanner val = new Scanner(System.in);
        System.out.println("Write a text to be encrypted below");
        text = val.nextLine();
        text = text.replaceAll("[^A-Za-z]+", "").toUpperCase();
        return text;
    }

    public static String Obify(){
        String ObifiedText = "";// replaces all vowels with "OB" and corresponding vowel
        int length = text.length();
        for (int i = 0; i < length; i++) {
            if (text.charAt(i) == 'A' || text.charAt(i) == 'E' || text.charAt(i) == 'I' // uses for loop to do so
                    || text.charAt(i) == 'O' || text.charAt(i)== 'U')
            {ObifiedText += "OB";
                ObifiedText += text.charAt(i);
            } else
                ObifiedText += text.charAt(i);
        }
        return ObifiedText;
    }

public static String caesarify(String text, int key) {

    String shiftA = shiftAlphabet(key);
    return shiftA;
}

    public static String shiftAlphabet(int shift) {
        int start = 0;
        if (shift < 0) {
            start = (int) 'Z' + shift + 1;
        } else {
            start = 'A' + shift;
        }
        String result = "";
        char currChar = (char) start;
        for (; currChar <= 'Z'; ++currChar) {
            result = result + currChar;
        }
        if (result.length() < 26) {
            for (currChar = 'A'; result.length() < 26; ++currChar) {
                result = result + currChar;
            }
        }
        return result;
    }
    }

问题是,您返回的是“shiftAlphabet”的值作为结果,而不是移动 obfuscated 文本.

改变方法caesarify,例如下面的片段,应该没问题。

public static String caesarify(String text, int key) {
  String shiftA = shiftAlphabet(key);

  char[] charArrayShifted = shiftA.toCharArray();
  char[] charArrayText = text.toCharArray();
  for(int i = 0; i < charArrayText.length; i++){
      // shift every element of charArrayText for the value of charArrayShifted for the key
      int shifted = (int) charArrayText[i] + (int)charArrayShifted[key-1];
      // if the sum is higher than the value of Z, subtract the value of A
      if (shifted > (int) 'Z'){
          shifted-=(int)'A';
      }
      charArrayText[i] = (char)shifted;
  }
return new String(charArrayText);
}