所以我做了这个任务,最后我转过来了,但在我的心里,我觉得我没有正确编写程序。它在吃我,我真的想明白我做错了什么。所以这里是代理人:我错过了什么使它成为一个简单的替代密码来加密和解密消息?
编写一个程序,可以使用 任意替换密码进行加密和解密。在这种情况下,加密阵列是所有可打印ASCII字符(包括 字符:空格)的随机混排 。
还包括了一个洗牌的想法:
import java.util.Arrays;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
Character[] original = new Character[]{'A', 'B', 'C', 'D', 'E'};
Character[] encrypted = new Character[]{'A', 'B', 'C', 'D', 'E'};
Collections.shuffle(Arrays.asList(encrypted));
System.out.println(Arrays.toString(encrypted));
}
}
,这就是我想出了:
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class Caesar {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter anything: ");
String input = keyboard.nextLine();
char[] original = input.toCharArray();
char[] encrypted = input.toCharArray();
String a = new String(original);
// Ask if we would like to encrypt
System.out.print("Shall we encrypt? (Y/N): ");
char selection = keyboard.next().charAt(0);
selection = Character.toUpperCase(selection);
if (selection == 'Y') {
// Encryption process
shuffleArray(encrypted);
System.out.print("Encrypted message: ");
for (int i = 0; i < encrypted.length; i++) {
System.out.print(encrypted[i]);
}
System.out.println();
System.out.print("Shall we decrypt? Y/N: ");
selection = keyboard.next().charAt(0);
selection = Character.toUpperCase(selection);
if (selection == 'Y') {
System.out.println("Decrypted message: " + a);
}
} else if (selection == 'N') {
System.out.print("Nothing was done to the text: " + a);
} else {
System.out.println("You must enter either Y or N!");
}
}
static void shuffleArray(char[] ar) {
Random random = new Random();
for (int i = ar.length - 1; i > 0; i--) {
int index = random.nextInt(i + 1);
// Simple swap
char a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
}
它开始作为一个恺撒密码,但我厌倦了和最后简单地使用随机洗牌,问题是加密仅适用于该实例。我希望能够可靠地解密消息,即使在其间发生其他实例。我几乎可以在脑海中看到解决方案,但这只是遥不可及。任何人都可以帮我连接点吗?