【发布时间】:2019-10-07 18:07:07
【问题描述】:
对于家庭作业,我必须计算种子数。我们得到一个输入文件,我们必须将其解密为输出文件。 我要做的是找到“种子”号,生成随机数,所以“加密”是随机的。
我们得到的唯一提示是原文是一本英文小说。我们必须用程序完全计算“种子”。 有人知道怎么做吗?
我想,一个每次都解密文件的 for 循环,直到输出文件没有“特殊”字符?但我不知道该怎么做。
我这里有加密/解密功能:
static char crypt(char input, int random, boolean encrypt)
{
assert random>=0&&random<=95 : "Random has to be between 0 and 95.";
if(input=='\n')
return '\n';
if((int)input>=32||(int)input<=127)
{
if(encrypt)
{
char inputEncrypted=(char)((input-32+random+96)%96+32);
return inputEncrypted;
} else
{
char inputDecrypted=(char)((input-32-random+96)%96+32);
return inputDecrypted;
}
}
return input;
}
}
我的主要功能是:
package ..;
public static void main(String[] args) throws IOException
{
Scanner scanner=new Scanner(System.in);
System.out.println("Give true if you want to encrypt, false for decrypt: ");
boolean encrypt=scanner.nextBoolean();
System.out.println("Give the input filename");
File inputFile=new File(scanner.next());
InputStreamReader reader=new InputStreamReader(new FileInputStream(inputFile));
System.out.println("Give the output filename");
File outputFile=new File(scanner.next());
OutputStreamWriter writer;
try
{
writer=new OutputStreamWriter(new FileOutputStream(outputFile));
{
Random generator=new Random(seed); //this one I have to calculate
int c;
while((c=reader.read())>=0)
{
writer.write(crypt((char)c,generator.nextInt(96),encrypt));
}
reader.close();
writer.close();
}
}
catch(FileNotFoundException e)
{
System.out.println("File is not found!");
}
scanner.close();
}
我们必须解密的 268Kb .txt 文件是:
r(8Of%?.)d*Ya |V?qS&@m$!wJKzfpu\CdQbir*80dB* J)6znu/gFf%,C=u u/:DP_,K@3'6])[eu=#y^+{WKK3k2N IOWwmW,H.0iF+!+J/'/-T'DQQg0N 2o71cRZ67X q!=dJ0s~ldq6}a{-Q C\H"{s@]ptRqU}A8y~gRHlf "@.H]bwXk|~e%NPIjr+KVw|3G0$Vx{%7Au#w\$
【问题讨论】:
-
使用您使用的方法,直到最后都不需要输出文件。只需将输入文件读入一个字符串,并使用您读入的每个字符测试特殊字符。如果您从输入文件中读取所有字符,并且没有一个字符被转换为特殊字符,则仅写入输出文件。跨度>
-
@Jordan 是的,这听起来很合乎逻辑,但我该怎么做呢?先做一个for循环,然后创建一个字符串,然后把文件读入这个字符串,然后如果字符串不包含@,'seed' = i。或者怎么做?
-
创建一个for循环,创建StringBuilder,一次将单个字符读入StringBuilder。如果您看到一个编码为特殊字符的字符,该字符将创建一个新的字符串生成器,请使用
continue跳转到循环的下一个迭代(请确保先关闭您的阅读器)。如果到了循环的末尾,则说明没有特殊字符,所以获取你的 StringBuilder 的字符串值,将其写入文件,然后跳出 for 循环。 -
我之前没有使用过 StringBuilder 或 Continue,所以我认为我不能使用它。我现在拥有的:
for(int i=1;i<=4711;i++) { Random generator=new Random(i); int d; while((d=reader.read())>=0) { String test=""; test=test+crypt((char)d,generator.nextInt(96),encrypt); if(!test.contains("@")){ //write into outputfile } -
@Jordan,你能帮帮我吗?现在有点绝望..
标签: java encryption generator