【发布时间】:2017-04-10 20:13:46
【问题描述】:
我正在尝试使用伪随机数通过 XOR 加密文本,然后将加密的文本写入文件。然后它再次读取文件,如果用户输入正确的密钥,它会解密文本。
但是我得到的只是?????。我做错了什么?
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Random;
import java.util.Scanner;
public class MainTest
{
public static void main(String[] args)
{
long seed = 754; // key
Random random = new Random(seed);
String message = "hello";
try
{
OutputStream os = new FileOutputStream("test.txt");
OutputStream bos = new BufferedOutputStream(os);
EncryptOutputStream eos = new EncryptOutputStream(bos);
for(int i = 0; i < message.length(); i++)
{
int z = random.nextInt();
eos.write(message.charAt(i), z);
}
eos.close();
InputStream is = new FileInputStream("test.txt");
InputStream bis = new BufferedInputStream(is);
DecryptInputStream dis = new DecryptInputStream(bis);
Scanner scanner = new Scanner(System.in);
System.out.print("Enter key: ");
long key = scanner.nextLong();
scanner.close();
random = new Random(key);
int c;
while((c = dis.read(random.nextInt())) != -1)
{
System.out.print((char)c);
}
dis.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
public class DecryptInputStream extends FilterInputStream
{
protected DecryptInputStream(InputStream in)
{
super(in);
}
public int read(int z) throws IOException
{
int c = super.read();
if(c == -1) return -1;
return c^z;
}
}
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class EncryptOutputStream extends FilterOutputStream
{
public EncryptOutputStream(OutputStream o)
{
super(o);
}
public void write(int c, int z) throws IOException
{
super.write(c^z);
}
}
【问题讨论】:
-
也许你应该使用
byte而不是int(不是random.nextInt()) -
您确定输入了正确的
seed进行解密吗?也许您应该只使用与加密相同的值。 -
我认为这不会在生产软件中使用,因为由于不安全的随机数生成器和低熵种子,它很容易被破坏。
标签: java encryption inputstream outputstream xor