我正在尝试通过暴力破解凯撒编码的基本 256 ASCII 文本。 有问题的文本是:
dy}uƒ0^u‡0b}q~K‹lvAlv‚}q~lv€‚Blvsxq‚ƒu„B0c‰}r|K‹lvBlvƒ‡yƒƒlv€‚Blvsxq‚ƒu„@0Q‚yq|K‹lvClv‚}q~lv€‚Blvsxq‚ƒu„@0\yru‚q„y~0cu‚yv‹l:lvq|„0dy}uƒ0^u‡0b}q~K‹lvDlvƒ‡yƒƒlv€‚Blvsxq‚ƒu„@0\yru‚q„y~0cq~ƒ‹l:lvq|„0Q‚yq|K‹lvElv‚}q~lv€‚@lvsxq‚ƒu„ABH0dy}uƒ0^u‡0b}q~K‹lvFlv~y|l
用这个小java程序:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class Run {
private static FileWriter fr;
static String b;
private static BufferedReader br;
public static void main(String[] args) throws IOException {
// encrypted file
File enc_f = new File("caesar.rtf.enc");
//decrypted file
File dec_f = new File("caesar.rtf.dec");
// init variables
String text_enc = new String();
String text_dec = new String();
// read file
br = new BufferedReader(new FileReader(enc_f));
for (String line; (line = br.readLine()) != null; text_enc += line);
char[] stringToCharArray = text_enc.toCharArray();
// parse file and convert string to char
for (int shift = 0; shift < 257; shift++) {
for (char output : stringToCharArray) {
// convert ascii to int
int ascii = (int) output;
// shift
ascii = ascii + shift;
ascii = ascii % 256;
// convert back to ascii
char chTemp = (char) ascii;
text_dec += chTemp;
}
// visual representation
text_dec += System.lineSeparator();
text_dec += System.lineSeparator();
text_dec += shift;
text_dec += System.lineSeparator();
System.out.println(shift);
// write decrypted file
fr = new FileWriter(dec_f);
fr.write(text_dec);
}
fr.close();
}
}
运行程序后,我得到了类次号239
的部分解密文本(这只是整个文件的一部分,以保持较短的执行时间):
Timeí Neí Roman;íí\f1\fíoman\fííí2\fchaííeí2 Símbol;íí\f2\fííiíí\fííí2\fchaííeí0 Aíial;íí\f3\fíoman\fííí2\fchaííeí0 Libeíaíion Seíifí\*\falí Timeí Neí Romaní;íí\f4\fííiíí\fííí2\fchaííeí0 Libeíaíion Saníí\*\falí Aíialí;íí\f5\fíoman\fííí0\fchaííeí128 Timeí Neí Roman;íí\f6\fnil\
可以看出,我可以读取 Time new Roman,但也可以读取不应该出现的 í
,而且我不明白为什么,就好像移位不会比所有的都正确一样。文本应该是错误的,而不仅仅是其中的一部分。加密的文本也可以被正确解密。
如果您有任何想法,我们将很乐意提供提示。
最佳答案
您犯了一个非常基本的错误:将二进制/字节与字符串混淆。
不存在“256 ASCII”这样的东西,ASCII 是 7 位,即在 [0..127] 内编码,前 32 个值和最后一个值是控制字符。
您所说的是字节,并且应该对这些字节执行操作。如果您在 Java 中对字节执行计算,它将自动位于 0..255 范围内。尽管字节没有“提升”为整数,但您必须小心,时不时地使用 (byte)
进行转换。
因此,除了最终打印输出之外,您的操作都应该以字节为单位。使用 Reader
和 Writer
可能会丢失数据,因为某些字符可能会被遗漏。只需直接使用流,然后在任何文本阅读器中查看输出。
您当然也可以利用输出位于某些字节值(有效字符编码)之间的事实来测试您的解决方案是否正确。
<小时/>请注意,我们无法为您进行测试,因为您输入的“字符串”可能已经损坏。如果您想在此处打印,请使用 Base 64 或十六进制对其进行编码。
关于java - 凯撒加密 ASCII 文本部分解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41789650/