我想使用Java来获得文件的MD5校验和。我真的很惊讶,但我还没有找到任何东西,显示如何获得一个文件的MD5校验和。
这是怎么做到的?
我想使用Java来获得文件的MD5校验和。我真的很惊讶,但我还没有找到任何东西,显示如何获得一个文件的MD5校验和。
这是怎么做到的?
当前回答
com.google.common.hash API提供:
为所有哈希函数提供统一的用户友好的API murmur3的32位和128位种子实现 Md5()、sha1()、sha256()、sha512()适配器,只需更改一行代码就可以在这些适配器之间切换。 goodFastHash(int bits),用于当你不关心你使用什么算法时 HashCode实例的通用实用程序,如combineOrdered / combineUnordered
阅读用户指南(IO解释,哈希解释)。
对于您的用例,Files.hash()计算并返回文件的摘要值。
例如,sha-1摘要计算(将sha-1更改为MD5以获得MD5摘要)
HashCode hc = Files.asByteSource(file).hash(Hashing.sha1());
"SHA-1: " + hc.toString();
请注意,crc32比md5快得多,所以如果您不需要加密安全的校验和,请使用crc32。还要注意,md5不应该用来存储密码之类的东西,因为它很容易被暴力破解,对于密码,应该使用bcrypt、scrypt或sha-256来代替。
对于使用散列的长期保护,默克尔签名方案增加了安全性,由欧盟委员会赞助的后量子密码学研究小组建议使用这种密码技术来长期保护量子计算机(参考)。
请注意,crc32的碰撞率比其他的更高。
其他回答
谷歌guava提供了一个新的API。找到下面的一个:
public static HashCode hash(File file,
HashFunction hashFunction)
throws IOException
Computes the hash code of the file using hashFunction.
Parameters:
file - the file to read
hashFunction - the hash function to use to hash the data
Returns:
the HashCode of all of the bytes in the file
Throws:
IOException - if an I/O error occurs
Since:
12.0
public static String MD5Hash(String toHash) throws RuntimeException {
try{
return String.format("%032x", // produces lower case 32 char wide hexa left-padded with 0
new BigInteger(1, // handles large POSITIVE numbers
MessageDigest.getInstance("MD5").digest(toHash.getBytes())));
}
catch (NoSuchAlgorithmException e) {
// do whatever seems relevant
}
}
String checksum = DigestUtils.md5Hex(new FileInputStream(filePath));
我们使用的代码类似于前面文章中使用的代码
...
String signature = new BigInteger(1,md5.digest()).toString(16);
...
但是,注意在这里使用BigInteger.toString(),因为它将截断前导零… (例如,尝试s = "27",校验和应该是"02e74f10e0327ad868d138f2b4fdd6f0")
我建议使用Apache Commons Codec,我用它替换了我们自己的代码。
我最近不得不为一个动态字符串这样做,MessageDigest可以以多种方式表示散列。为了获得文件的签名,就像你会得到md5sum命令,我必须做这样的事情:
try {
String s = "TEST STRING";
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(s.getBytes(),0,s.length());
String signature = new BigInteger(1,md5.digest()).toString(16);
System.out.println("Signature: "+signature);
} catch (final NoSuchAlgorithmException e) {
e.printStackTrace();
}
这显然没有回答你关于如何专门为一个文件做这件事的问题,上面的答案很好地处理了这个问题。我只是花了很多时间使和看起来像大多数应用程序显示它,并认为您可能会遇到同样的麻烦。