【问题标题】:Why does ZipInputStream.getNextEntry() return null?为什么 ZipInputStream.getNextEntry() 返回 null?
【发布时间】:2021-07-08 15:57:32
【问题描述】:

我有一个 AES 加密的 zip 文件。解密后,我留下了一个包含 zip 内容的 byte[]。但是当我尝试使用 ByteArrayInputStream 解压缩它时,ZipInputStream.getNextEntry() 会立即返回 null。调试,我看到我的 byte[] 没有所需的本地文件头签名,即

静态长 LOCSIG = 0x04034b50L; // "PK\003\004"

所以 ZipInputStream.getNextEntry() 返回 null。

但是,如果我将这些解密的字节写入文件,然后使用传递给 ZipInputStream() 的 FileInputStream(),则一切正常。以下是我当前的代码。任何人都可以建议一种无需先写入临时文件即可解压缩的方法吗?

    byte[] data = AESUtil.decryptInputStream(...);
    ByteArrayInputStream bis = new ByteArrayInputStream(data);
    ZipInputStream stream = new ZipInputStream(bis);
    ZipEntry entry;
    while ((entry = stream.getNextEntry()) != null) {
        ...
    }

【问题讨论】:

  • 当我使用 CipherInputStream 时也会发生同样的事情。 ZipInputStream.readLOC() 在此比较中返回 null: ** if (get32(tmpbuf, 0) != LOCSIG) { return null; } **
  • 我需要更正我最初的帖子 - 并道歉:我错误地写道,如果我将解密的字节写入文件然后使用 FileInputStream 和 ZipInputStream 一切正常。我实际上并没有尝试过——我只是在解密的文件上运行了 UNIX 命令“解压缩”,然后就可以了。我只是假设 - 错误地 - 如果是这种情况,FileInputStream/ZipInputStream 会起作用。所以,总而言之,看起来我正在写一个解密的 zip 文件,其中包含“zip”程序可以处理的字节,但 ZipInputStream 不能。
  • 我应该澄清一下:使用 CipherInputStream 而不是 ByteArrayOutputStream。我怀疑问题可能出在您的 AWSUtil.decryptInputStream 方法中。所以只需使用new ZipInputStream(new CipherInputStream(originalInputStream, cipher))
  • @VGR 我理解你的原始帖子。我所做的正是您在随后的澄清中指定的。但我仍然得到相同的结果 - ZipInputStream.getnextEntry() 返回 null,因为字节流的前 32 个字节与某些预期的标头值 0x04034b50L 不匹配。但是独立的“解压缩”程序可以解压缩具有完全相同字节的文件。我想我可能需要尝试另一个库(不是有 apache commons zip/unzip lib吗?)

标签: java zipinputstream


【解决方案1】:

我得出的结论是 ZipInputStream 不够灵活。当我用 Apache Commons 的压缩类替换上面的代码时,一切正常。下面是使用该库和相同字节数组的工作实现:

byte[] data = AESUtil.decryptInputStream(...);
SeekableInMemoryByteChannel inMemoryByteChannel = new SeekableInMemoryByteChannel(data);
ZipFile zipFile = new ZipFile(inMemoryByteChannel);
Iterator<ZipArchiveEntry> iterator = = zipFile.getEntriesInPhysicalOrder().asIterator();
while (iterator.hasNext()) {
    ...
}

【讨论】:

    猜你喜欢
    • 2013-03-09
    • 2022-12-26
    • 2016-12-28
    • 2015-11-25
    • 2015-07-04
    • 2019-09-29
    • 2015-02-25
    • 2015-10-21
    • 2021-08-12
    相关资源
    最近更新 更多