1

我有一个获取 zip 文件的 md5 校验和的 Android 应用程序。我用它来比较文件和服务器上的文件。我的问题是每次我尝试为同一个文件生成 md5 时,校验和都是不同的。我在这里发布我的方法。你能告诉我有什么问题吗?

private static String fileMD5(String filePath) throws NoSuchAlgorithmException, IOException {
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(filePath);
            byte[] buffer = new byte[1024];
            MessageDigest digest = MessageDigest.getInstance("MD5");
            int numRead = 0;
            while (numRead != -1) {
                numRead = inputStream.read(buffer);
                if (numRead > 0)
                    digest.update(buffer, 0, numRead);
            }
            byte [] md5Bytes = digest.digest();
            return convertHashToString(md5Bytes);
        } catch (Exception e) {
            return "ERROR";
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception e) { }
            }
        }
    }

    private static String convertHashToString(byte[] md5Bytes) {
        String returnVal = "";
        for (int i = 0; i < md5Bytes.length; i++) {
            returnVal += Integer.toString(( md5Bytes[i] & 0xff ) + 0x100, 16).substring(1);
        }
        return returnVal;
    }
4

1 回答 1

0

我试图解决同样的问题。我不知道如何解决它,但我知道原因:)。

原因是 zip 文件至少包含有关文件的时间戳信息。这就是改变你 md5sum 的原因。每个 zip 条目都是相同的,但此元数据信息会更改 md5 的结果。

可能您已经在其他地方找到了答案。

于 2015-12-10T20:12:45.650 回答