java - 将 CipherInputStream 写入文本文件
问题描述
我正在尝试解密存储在文本文件中的加密数据。我使用相同的密钥和IV进行加密和解密,并通过配置文件传输。
当我将 CipherInputStream 打印到控制台时,我确实得到了一些内容,但是当我尝试将其写入文本文件时,我没有得到任何内容。
这是我的问题的一段代码:
File encryptedData = new File("C:\\Users\\Victoria\\Desktop\\encryptedData.txt");
File decryptedData = new File("C:\\Users\\Victoria\\Desktop\\decryptedData.txt");
FileInputStream inputStream = new FileInputStream(encryptedData);
byte[] inputBytes = new byte[(int) decryptedData.length()];
inputStream.read(inputBytes);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, newkey, newiv, SecureRandom.getInstance("SHA1PRNG"));
CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher);
FileOutputStream outputStream = new FileOutputStream(decryptedData);
System.out.println("cipherInputStream: " + cipherInputStream);
// Writing the decrypted content to an output file
byte[] buff = new byte[1024 * 10];
int length;
while ((length = cipherInputStream.read(buff)) > 0) {
outputStream.write(buff, 0, length);
}
bufin.close();
outputStream.close();
cipherInputStream.close();
有什么解决办法吗?谢谢!
解决方案
存储在文本文件中的加密数据
这在术语上已经是矛盾的了。加密数据是二进制的,而不是文本的,不应存储在带有.txt
扩展名的文件中。
byte[] inputBytes = new byte[(int) decryptedData.length()];
这行代码毫无意义。您还不知道解密数据将持续多长时间。解密后的文件甚至可能不存在,在这种情况下,这将产生一个长度为零的数组;或者它可能与即将生产的不同,在这种情况下,它的长度是错误的。
inputStream.read(inputBytes);
删除这一行和它之前的那一行。
- 它读入一个数组,该数组的大小最好是解密数据的大小,这对于加密数据来说是错误的大小,最坏的情况是错误的大小,甚至是零长度,如上所示。
- 它可能会读取输入,直到错误大小的缓冲区已满,然后您 (a) 完全忽略读取的数据并 (b) 尝试进一步读取相同的流,这将在解密循环中失败,或者最多产生不正确的输出,因为您可能没有解密所有数据。
当我将 CipherInputStream 打印到控制台时,我确实得到了一些内容
不,你没有。你得到一条一般形式的数据CipherInputStream@0011223344
,它只是调用的结果,CipherInputStream.toString()
不包含任何“内容”。
推荐阅读
- angular - 带有“道具”或函数参数类型错误的 createAction
- javascript - javascript代码在oninput属性中不起作用
- dart - 为什么 Dart 不能在编译时检查数组绑定?
- performance - 如何在 teamcity 中设置超时和活动的多运行构建器
- django - Django 过滤 URL 和 VIEWS - “在 /collection/... 找不到页面”
- java - 我不懂一行编程代码
- php - 如何更正在 PDO 中运行准备好的语句的功能
- html - 在固定位置显示按钮
- java - 使用 for 循环将重复项插入到 StringBuilder 的方法
- reactjs - 子组件不会重新渲染