我想使用Java获取文件的MD5校验和。但是我很惊讶,我找不到任何展示如何获取文件的MD5校验和的资料。
请问该怎么做?
我想使用Java获取文件的MD5校验和。但是我很惊讶,我找不到任何展示如何获取文件的MD5校验和的资料。
请问该怎么做?
...
String signature = new BigInteger(1,md5.digest()).toString(16);
...
注意不要在这里使用BigInteger.toString()
,因为它会截断前导零...
(例如,尝试s =“27”
,校验和应为“02e74f10e0327ad868d138f2b4fdd6f0”
)
我支持使用Apache Commons编解码器的建议,我用它替换了我们自己的代码。
这是一个非常快速和干净的Java方法,不依赖于外部库:
(如果您需要,只需将MD5替换为SHA-1、SHA-256、SHA-384或SHA-512即可。)
public String calcMD5() throws Exception{
byte[] buffer = new byte[8192];
MessageDigest md = MessageDigest.getInstance("MD5");
DigestInputStream dis = new DigestInputStream(new FileInputStream(new File("Path to file")), md);
try {
while (dis.read(buffer) != -1);
}finally{
dis.close();
}
byte[] bytes = md.digest();
// bytesToHex-method
char[] hexChars = new char[bytes.length * 2];
for ( int j = 0; j < bytes.length; j++ ) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
new BigInteger(1, bytes).toString(16)
。 - assylias以下是一种方便的方法,它利用了Java 9中的InputStream.transferTo()
和Java 11中的OutputStream.nullOutputStream()
。它不需要外部库,也不需要将整个文件加载到内存中。
public static String hashFile(String algorithm, File f) throws IOException, NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance(algorithm);
try(BufferedInputStream in = new BufferedInputStream((new FileInputStream(f)));
DigestOutputStream out = new DigestOutputStream(OutputStream.nullOutputStream(), md)) {
in.transferTo(out);
}
String fx = "%0" + (md.getDigestLength()*2) + "x";
return String.format(fx, new BigInteger(1, md.digest()));
}
并且
hashFile("SHA-512", Path.of("src", "test", "resources", "some.txt").toFile());
返回
"e30fa2784ba15be37833d569280e2163c6f106506dfb9b07dde67a24bfb90da65c661110cf2c5c6f71185754ee5ae3fd83a5465c92f72abd888b03187229da29"
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));
另一种实现方式:Java中快速MD5实现
String hash = MD5.asHex(MD5.getHash(new File(filename)));
MD5.asHex()
方法。 - cbaldanpublic String checksum(File file) {
try {
InputStream fin = new FileInputStream(file);
java.security.MessageDigest md5er =
MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024];
int read;
do {
read = fin.read(buffer);
if (read > 0)
md5er.update(buffer, 0, read);
} while (read != -1);
fin.close();
byte[] digest = md5er.digest();
if (digest == null)
return null;
String strDigest = "0x";
for (int i = 0; i < digest.length; i++) {
strDigest += Integer.toString((digest[i] & 0xff)
+ 0x100, 16).substring(1).toUpperCase();
}
return strDigest;
} catch (Exception e) {
return null;
}
}
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.xml.bind.DatatypeConverter;
public class Checksum {
/**
* Generates an MD5 checksum as a String.
* @param file The file that is being checksummed.
* @return Hex string of the checksum value.
* @throws NoSuchAlgorithmException
* @throws IOException
*/
public static String generate(File file) throws NoSuchAlgorithmException,IOException {
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
messageDigest.update(Files.readAllBytes(file.toPath()));
byte[] hash = messageDigest.digest();
return DatatypeConverter.printHexBinary(hash).toUpperCase();
}
public static void main(String argv[]) throws NoSuchAlgorithmException, IOException {
File file = new File("/Users/foo.bar/Documents/file.jar");
String hex = Checksum.generate(file);
System.out.printf("hex=%s\n", hex);
}
}
示例输出:
hex=B117DD0C3CBBD009AC4EF65B6D75C97B
<checksum file="${jarFile}" todir="${toDir}"/>
jarFile是您想要生成MD5的JAR文件,toDir是您想要放置MD5文件的目录。
谷歌 guava 提供了一个新的 API。请找到下面的 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