zip文件的MD5哈希 [英] MD5 hash for zip files

查看:1107
本文介绍了zip文件的MD5哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在Java中为.zip文件生成MD5哈希?我发现的所有示例都是针对.txt文件的.

Is it possible to generate MD5 hash for .zip files in java? All the examples I found were for .txt files.

我想知道何时解压缩数据,编辑文件,再次压缩文件并找到哈希,它会与原始文件不同吗?

I want to know when we unzip the data, edit a file, again zip it and find the hash, will it be different from the original one?

推荐答案

您可以为任意文件创建MD5哈希,而与文件类型无关.哈希仅占用 any 个字节流,根本不解释其含义.因此,您可以使用为.txt文件找到的示例,并将其应用于.zip文件.

You can create MD5 hashes for any arbitrary file, independently of the file type. The hash just takes any byte stream and doesn't interpret its meaning at all. So you can use the examples you have found for .txt files and apply them to .zip files.

是的,在.zip中编辑文件很可能会更改.zip文件的MD5-尽管由于哈希冲突而不能保证.但这只是哈希的一般属性,与压缩无关.

And yes, editing a file inside the .zip will most likely change the MD5 of the .zip file - even though that's not guaranteed, due to hash collisions. But that's just a general property of hashes and has nothing to do with the zipping.

但是请注意,即使内容未更改,重新压缩文件也可能会更改MD5哈希值.这是因为即使解压缩的文件与以前的文件相同,压缩的文件也可能会根据所使用的压缩算法及其参数而有所不同.

Note, however, that rezipping files may change the MD5 hash, even if the content has not changed. That's because even though the unzipped files are the same as before, the zipped file may vary depending on the used compression algorithm and its parameters.

编辑(根据您的评论):

如果要避免在重新压缩时更改MD5哈希值,则必须在未压缩文件上运行MD5.您只需使用流就可以即时进行操作,而无需实际将文件写入磁盘. ZipInputStream可以帮助您.一个简单的代码示例:

If you want to avoid those changing MD5 hashes on rezipping, you have to run the MD5 on the unzipped files. You can do that on-the-fly without actually writing the files to disk, just by using streams. ZipInputStream helps you. A simple code example:

    InputStream theFile = new FileInputStream("example.zip");
    ZipInputStream stream = new ZipInputStream(theFile);
    try
    {
        ZipEntry entry;
        while((entry = stream.getNextEntry()) != null)
        {
            MessageDigest md = MessageDigest.getInstance("MD5");
            DigestInputStream dis = new DigestInputStream(stream, md);
            byte[] buffer = new byte[1024];
            int read = dis.read(buffer);
            while (read > -1) {
                read = dis.read(buffer);
            }
            System.out.println(entry.getName() + ": "
                    + Arrays.toString(dis.getMessageDigest().digest()));
        }
    } finally { stream.close(); }

这篇关于zip文件的MD5哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆