罐子不同,但他们不应该

Jar differs but they should not

我有一种创建 jar 的方法。

public class Test {

    public static void main(String[] args) throws Exception {
        aha();
        aha();
        aha();
        aha();
        Thread.sleep(5000);
        aha();
    }

    private static void aha() throws IOException, NoSuchAlgorithmException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        JarOutputStream jos = new JarOutputStream(baos);
        jos.putNextEntry(new ZipEntry("sd"));
        jos.write("sdf".getBytes());
        jos.close();
        MessageDigest md = MessageDigest.getInstance("sha1");
        byte[] digest = md.digest(baos.toByteArray());
        for (byte b : digest) {
            System.out.print("," + b);
        }
        System.out.println();
    }
}

输出为:

,-57,-44,59,113,-126,-15,71,62,-90,-120,27,36,-3,69,26,-55,63,107,-93,102
,-57,-44,59,113,-126,-15,71,62,-90,-120,27,36,-3,69,26,-55,63,107,-93,102
,-57,-44,59,113,-126,-15,71,62,-90,-120,27,36,-3,69,26,-55,63,107,-93,102
,-57,-44,59,113,-126,-15,71,62,-90,-120,27,36,-3,69,26,-55,63,107,-93,102
,-124,-26,-79,-28,-34,77,-72,83,92,53,30,-13,95,21,-92,55,70,24,-72,39

我需要相同的摘要,但最后一个摘要不同。如何成为可重现的哈希值?

虽然几乎看不见,但如果你把一个ZipEntry写到一个JarOutputStream,底层的ZipOutputStream会为你初始化最后修改时间。

if (e.xdostime == -1) {
    // by default, do NOT use extended timestamps in extra
    // data, for now.
    e.setTime(System.currentTimeMillis());
}

您必须手动初始化时间 setTime 得到一个恒定的结果。