在Java程序中计算zip文件的md5哈希值

时间:2011-03-14 10:48:05

标签: java md5

我有一个zip文件,在我的Java代码中我想计算zip文件的md5哈希值。有没有我可以用于此目的的java库?一些例子将非常感激。

谢谢

2 个答案:

答案 0 :(得分:4)

几周前,我在这篇文章中得到了这篇文章:

http://www.javalobby.org/java/forums/t84420.html

只是让它成为一个stackoveflow:

public static void main(String[] args) throws NoSuchAlgorithmException, FileNotFoundException {
MessageDigest digest = MessageDigest.getInstance("MD5");
File f = new File("c:\\myfile.txt");
InputStream is = new FileInputStream(f);                
byte[] buffer = new byte[8192];
int read = 0;
try {
    while( (read = is.read(buffer)) > 0) {
        digest.update(buffer, 0, read);
    }       
    byte[] md5sum = digest.digest();
    BigInteger bigInt = new BigInteger(1, md5sum);
    String output = bigInt.toString(16);
    System.out.println("MD5: " + output);
}
catch(IOException e) {
    throw new RuntimeException("Unable to process file for MD5", e);
}
finally {
    try {
        is.close();
    }
    catch(IOException e) {
        throw new RuntimeException("Unable to close input stream for MD5 calculation", e);
    }
}       
}

答案 1 :(得分:0)

还有一个选项可以用 Apache Codec 那样做

final String sha256 = DigestUtils.sha256Hex(new FileInputStream(file))