Java课程Enigma项目:Rotor密码无法正确加密的修复求助
Enigma转子加密错误修复:字符位置未更新导致的映射错误
问题分析
你的代码核心问题是在多转子链式加密过程中,始终使用初始字符的位置(loc=14),而非前一个转子输出字符的位置作为下一个转子的输入索引。从输出日志可以看到,三次转子循环中loc始终是14,这完全不符合Enigma的加密逻辑——每个转子的输出应该作为下一个转子的输入,即需要更新当前字符在原字母表中的位置,再传入下一个转子处理。
修复方案
在每次转子加密后,更新loc为当前输出字符在原字母表中的位置,确保下一个转子使用正确的索引进行映射。
修改后的代码如下:
// 使用德军早期部署的Enigma转子 public static String RotorCipher(ArrayList<ArrayList<Character>> affine, String input){ String constructor = ""; ArrayList<ArrayList<Character>> affine2 = new ArrayList<ArrayList<Character>>(affine); ArrayList<Character> list = new ArrayList<Character>(affine.get(0)); // 大写字母表 affine2.remove(0); for(char x : input.toCharArray()){ int loc = list.indexOf(x); if(loc == -1){ constructor += ""+x; // 非字母字符直接保留 } else { for(ArrayList<Character> rotor : affine2){ System.out.println(rotor); System.out.println(loc); System.out.print(x + " to "); x = AffineCipher(list, rotor, x+"").toCharArray()[0]; // 通过AffineCipher处理转子映射 System.out.println(x); // 关键修复:更新loc为当前输出字符在原字母表中的位置 loc = list.indexOf(x); } } constructor += x+""; } return constructor; }
额外检查点
如果修复后仍未得到预期的S,需要验证两个关键点:
- 确认
AffineCipher的映射逻辑是否符合Enigma转子规则:输入字符在原字母表的位置,对应转子列表中同索引的字符,而非反向映射。 - 核对你使用的转子接线表是否与德军早期Enigma(转子I、II、III)的官方接线完全一致。
内容的提问来源于stack exchange,提问作者SonG0D
相关产品推荐
相关产品推荐

