【发布时间】:2014-05-07 12:10:05
【问题描述】:
我正在尝试编写一些辅助方法来处理加密文件的读写。我有两种方法可以成功实现这一点并返回一个 InputStream 或一个 OutputStream (它们实际上是 Cipher 版本),我可以使用它们来读取或写入文件。我已经确认这些方法在使用对象流包装并用于读取和写入加密对象到文件时非常有效。
但是,当我尝试从加密的文本文件中读取时,就会出现问题。我可以验证我提供给它的字符串是否被加密并写入正确的文件,但是当我尝试从这个文件中读回时,BufferedReader 报告一个 EOF (null)。 InputStream.available() 方法返回 0。我可以确保文件在那里,正在被找到,并且 InputStream 本身不为空。谁能告诉我这是什么原因造成的?
读/写加密对象效果很好(CorruptedStreamException 在这里很好):
private static void testWriteObject() {
String path = "derp.derp";
Derp start = new Derp("Asymmetril: " + message, 12543, 21.4, false);
FilesEnDe.writeEncryptedObject(key, "derp.derp", start);
echo("original");
echo(">"+start);
Object o;
try {
ObjectInputStream ois = new ObjectInputStream(ResourceManager.getResourceStatic(path));
o = ois.readObject();
echo("encrypted");
echo(">"+o);
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
o = FilesEnDe.readEncryptedObject(key, path);
echo("decrypted");
echo(">"+o);
}
输出:
original
>Asymmetril: WE CAME, WE SAW, WE CONQUERED.; 12543; 21.4; false
[RM] > Trying to load resource: derp.derp
java.io.StreamCorruptedException
[RM] > Trying to load resource: derp.derp
decrypted
>Asymmetril: WE CAME, WE SAW, WE CONQUERED.; 12543; 21.4; false
尝试解密文本文件不行(注意加密后的文本是可读的):
private static void testWriteFile() {
String path = "EncryptedOut.txt";
BufferedReader bis1, bis2;
try {
BufferedOutputStream os = new BufferedOutputStream(FilesEnDe.getEncryptedOutputStream(key, path));
os.write(message.getBytes());
os.flush();
os.close();
} catch (IOException e1) {
e1.printStackTrace();
}
echo("original");
echo(">"+message);
try {
bis1 = new BufferedReader (new InputStreamReader(ResourceManager.getResourceStatic(path)));
echo("encrypted");
echo(">" + bis1.readLine());
bis1.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
InputStream is = FilesEnDe.getEncryptedInputStream(key, path);
InputStreamReader isr = new InputStreamReader(is);
bis2 = new BufferedReader (isr);
echo("bits in stream? " + is.available());
echo("decrypted");
echo(">"+bis2.readLine());
bis2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
输出:
original
>WE CAME, WE SAW, WE CONQUERED.
encrypted
>¤ƒ]£¬Vß4E?´?ùûe
[RM] > Trying to load resource: EncryptedOut.txt
bytes in stream? 0
decrypted
>null
用于创建 CipherInputStream 的代码:
public static InputStream getEncryptedInputStream(String key, String path) {
try {
InputStream is = ResourceManager.getResourceStatic(path);
SecretKeySpec keyspec = new SecretKeySpec(getHash(key),"AES");
Cipher c = Cipher.getInstance("AES");
c.init(Cipher.DECRYPT_MODE, keyspec);
return new CipherInputStream(is,c);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
return null;
}
当我尝试使用密码输入流解密文件并检索原始字符串时出现问题。
【问题讨论】:
标签: java inputstream bufferedreader