The getDigest() method of MessageDigestForFile has three parameters. The first is the InputStream of the file that we're going to read from. The second parameter is our MessageDigest. The third parameter is the size of the byte array that we'll use to read from the InputStream and update the MessageDigest. The getDigest() method first resets the MessageDigest to be sure that it is fresh. It reads the bytes of the file to update the MessageDigest. We get the resulting digest from the MessageDigest and convert this to a String that we return from the method.
MessageDigestForFile.java
package test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.commons.codec.binary.Hex;
public class MessageDigestForFile {
public static void main(String[] args) throws NoSuchAlgorithmException, FileNotFoundException, IOException {
String file = "httpd-2.2.6-win32-src-r2.zip";
MessageDigest md = MessageDigest.getInstance("MD5");
String digest = getDigest(new FileInputStream(file), md, 2048);
System.out.println("MD5 Digest:" + digest);
}
public static String getDigest(InputStream is, MessageDigest md, int byteArraySize)
throws NoSuchAlgorithmException, IOException {
md.reset();
byte[] bytes = new byte[byteArraySize];
int numBytes;
while ((numBytes = is.read(bytes)) != -1) {
md.update(bytes, 0, numBytes);
}
byte[] digest = md.digest();
String result = new String(Hex.encodeHex(digest));
return result;
}
}The execution of MessageDigestForFile generates the following console output:
MD5 Digest:301d61853fc9ce94bbfb55b56c218d06
本文介绍了一种使用Java实现的MD5摘要算法来为文件生成唯一标识的方法。通过MessageDigest类,结合Apache Commons Codec库中的Hex类将MD5摘要转换为十六进制字符串。该方法首先重置MessageDigest确保其状态清新,然后读取文件字节更新摘要,最后返回转换后的字符串。
880

被折叠的 条评论
为什么被折叠?



