不知道我哪里出错了,但我的程序应该是一个流密码,它接受一个 input.txt 文件chars
并将其加密为数字,然后将其解密回chars
.
我的问题是我输入:
java Program4 -e 71 < inp.txt > out.txt
(将 txt 加密到输出文件并且工作正常,)输入文件如下所示:
guess what? Chicken butt
输出文件如下所示:
222 204 220 202 202 153 206 209 216 205 134 153 250 209 208 218 210 220 215 153 219 204 205 205
然后当我解密文件时..
java Program4 -d 71 < out.txt
结果是这样的:
g E ? ? 8 º ? Ä ì ß ê ( ? ½ ^ ~ ? ? X ?
我不知道我做错了什么,但我猜这与我的解密方法有关,或者我的加密如何在某些值上给出相同的数字?我真的很感激任何帮助!
import java.util.Scanner;
import java.util.Random;
public class Program4
{
public static void main(String[] args)
{
if(args.length < 2)
{
usage();
}
else if(args[0].equals("-e"))
{
encrypt(args);
}
else if(args[0].equals("-d"))
{
decrypt(args);
}
}
//Intro (Usage Method)
public static void usage()
{
System.out.println("Stream Encryption program by my name");
System.out.println("usage: java Encrypt [-e, -d] < inputFile > outputFile" );
}
//Encrypt Method
public static void encrypt(String[] args)
{ Scanner scan = new Scanner(System.in);
String key1 = args[1];
long key = Long.parseLong(key1);
Random rng = new Random(key);
int randomNum = rng.nextInt(256);
while (scan.hasNextLine())
{
String s = scan.nextLine();
for (int i = 0; i < s.length(); i++)
{
char allChars = s.charAt(i);
int cipherNums = allChars ^ randomNum;
System.out.print(cipherNums + " ");
}
}
}
//Decrypt Method
public static void decrypt(String[] args)
{ String key1 = args[1];
long key = Long.parseLong(key1);
Random rng = new Random(key);
Scanner scan = new Scanner(System.in);
while (scan.hasNextInt())
{
int next = scan.nextInt();
int randomNum = rng.nextInt(256);
int decipher = next ^ randomNum;
System.out.print((char)decipher + " ");
}
}
}