POI XSSF / XLSX 散列不确定性与 MessageDigest SHA-256

POI XSSF / XLSX hashing indeterminism with MessageDigest SHA-256

使用 MessageDigest SHA-256 实现获取 POI XLSX 格式的确定性哈希值似乎有问题,即使对于空的 ByteArray 流也是如此。这是随机发生的,经过数百甚至数千次迭代。

用于重现问题的相关代码片段:

// TestNG FileTest:
@Test(enabled = true) // indeterminism at random iterations, such as 400 or 1290
public void emptyXLSXTest() throws IOException, NoSuchAlgorithmException {
    final Hasher hasher = new HasherImpl();
    boolean differentSHA256Hash = false;
    for (int i = 0; i < 10000; i++) {
        final ByteArrayOutputStream excelAdHoc1 = BusinessPlanInMemory.getEmptyExcel("xlsx");
        final ByteArrayOutputStream excelAdHoc2 = BusinessPlanInMemory.getEmptyExcel("xlsx");

        byte[] expectedByteArray = excelAdHoc1.toByteArray();
String expectedSha256 = hasher.sha256(expectedByteArray);
byte[] actualByteArray = excelAdHoc2.toByteArray();
String actualSha256 = hasher.sha256(actualByteArray);

if (!expectedSha256.equals(actualSha256)) {
            differentSHA256Hash = true;
            System.out.println("ITERATION: " + i);
            System.out.println("EXPECTED HASH: " + expectedSha256);
            System.out.println("ACTUAL HASH: " + actualSha256);
            break;
        }
    }
    Assert.assertTrue(differentSHA256Hash, "Indeterminism did not occur");
}

引用的Hasher和POI代码:

// HasherImpl class:
public String sha256(final InputStream stream) throws IOException, NoSuchAlgorithmException {
    final MessageDigest digest = MessageDigest.getInstance("SHA-256");
    final byte[] bytesBuffer = new byte[300000]; 
    int bytesRead = -1;
    while ((bytesRead = stream.read(bytesBuffer)) != -1) {
        digest.update(bytesBuffer, 0, bytesRead);
    }
    final byte[] hashedBytes = digest.digest();
    return bytesToHex(hashedBytes);
}

试图消除由于创建时间等元数据造成的不确定性,但无济于事:

// POI BusinessPlanInMemory helper class:
public static ByteArrayOutputStream getEmptyExcel(final String fileextension) throws IOException {
    Workbook wb;

    if (fileextension.equals("xls")) {
        wb = new HSSFWorkbook();
    }
    else {
        wb = new XSSFWorkbook();
        final POIXMLProperties props = ((XSSFWorkbook) wb).getProperties();
        final POIXMLProperties.CoreProperties coreProp = props.getCoreProperties();
        coreProp.setCreated("");
        coreProp.setIdentifier("1");
        coreProp.setModified("");
    }

    wb.createSheet();

    final ByteArrayOutputStream excelStream = new ByteArrayOutputStream();
    wb.write(excelStream);
    wb.close();
    return excelStream;
}

HSSF / XLS 格式似乎不受所述问题的影响。 有没有人知道,如果不是 POI 本身的错误,可能是什么原因造成的?基本上,上面的代码是指 https://poi.apache.org/spreadsheet/examples.html商业计划示例

感谢您的意见!

这不是一个明确的答案,但这是我怀疑会发生什么:

docx 和 xlsx 文件格式基本上是一堆压缩的 xml 文件。将它们重命名为 .zip 并使用您最喜欢的压缩工具打开时,可以很容易地看到这一点。

在检查由 word 创建的文件时,我注意到存档中包含的所有文件的更改时间戳总是 1980-01-01 00:00:00,而在使用 POI 创建的文件中,它将显示文件创建的实际时间戳。

所以我怀疑您的问题是在 excelAdHoc1excelAdHoc2 中的一个或多个文件之间存在时间戳差异时发生的。在创建一个或另一个文件时时钟切换到下一秒时可能会发生这种情况。

这不会影响 XLS 文件,因为 HSSF 格式不是 "zipped xml" 类型,因此不包含任何可能具有不同时间戳的嵌套文件。

要在写入文件后更改时间戳,您可以尝试使用“java.util.zip”-package。我还没有测试过,但这应该可以解决问题:

ZipFile file = new ZipFile(pathToFile);
Enumeration<ZipEntry> e = file.entries();
while(e.hasMoreElements()) {
    ZipEntry entry = e.nextElement();
    entry.setTime(0L);
}

好的,根据在此处找到的一些示例,我找到了一种重置所有 XSLX 文件条目文件时间属性的方法。不幸的是,似乎只有文件条目可以通过 ZipFile 或 OPCPackage 等方法访问。我找不到同时访问和重置存档中的文件夹的解决方案,这些文件夹也具有不同的时间属性。

到目前为止,我没有成功消除 POI 生成的 XLSX 档案的不同属性,无法从两个其他方面相同的文件中获得相同的 SHA256 哈希值,原因似乎是不同的属性。

private void resetOPCPTimeAttributes(File file)
        throws InvalidFormatException, IOException, OpenXML4JException, XmlException {

    OPCPackage opcp = ZipPackage.open(file);
    resetZipfileContentTimeAttributes(opcp.getParts());

    opcp.flush();
    opcp.close();
}

private void resetZipfileContentTimeAttributes(List<PackagePart> parts) throws InvalidFormatException {

    ArrayList<PackagePart> subParts = null;
    for (PackagePart part: parts) {

        PackageProperties props = part.getPackage().getPackageProperties();
        props.setLastModifiedByProperty("");
        props.setCreatedProperty("");
        props.setModifiedProperty("");

        subParts = part.getPackage().getParts();

        while (subParts != null) {
            resetZipfileContentTimeAttributes(subParts);
        }
    }
}

编辑:

与此同时(直到我或其他人找到在 Zip 存档中处理文件夹元数据的解决方案),我已切换到此处的深度比较解决方案:Comparing XLSX files