【发布时间】:2021-10-18 21:43:51
【问题描述】:
假设我们有 InputStream 读取数据,OutputStream 写入数据和 Cipher。 我们确实以这种方式加密数据:
int bs = 4096;
Cipher cipher = ...;
InputStream input = ...;
OutputStream output = ...;
int count = 0;
byte[] buffer = new byte[bs];
while (true)
{
count = input.read(buffer, 0, bs);
if (count < bs)
break;
byte[] encrypted = cipher.update(buffer, 0, count);
output.write(encrypted, 0, encrypted.length);
}
if (count > 0)
{
byte[] final = cipher.doFinal(buffer, 0, count);
output.write(final, 0, final.length);
}
但是如果数据正好是 4096 字节或倍数呢?这样我们将调用 update 但下一次迭代我们从输入中得到 count = -1 ,因为什么都没有了,所以我们跳过 doFinal() 部分。如何防止跳过 doFinal()?或者我们可以只调用 0 长度的 doFinal(buffer, 0, 0) 吗?
【问题讨论】:
-
我认为更好的解决方案是迭代缓冲区,而不是 while(true)。或者分离成一个函数或方法,它会解决你的问题。
标签: java encryption stream