【问题标题】:Calculate md5 hash of a zip file in Java program在Java程序中计算一个zip文件的md5哈希
【发布时间】:2011-03-14 10:48:05
【问题描述】:

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

谢谢

【问题讨论】:

  • 能否请您查看页面右下角的“相关”部分?谢谢。
  • 我查看了相关问题,但找不到与在 Java 中散列文件相关的问题。有一些用于 Java 中的字符串和 Perl 中的文件等,但没有用于 Java 中的文件。
  • 很抱歉刚刚找到一个:stackoverflow.com/questions/304268/…

标签: java md5


【解决方案1】:

几周前我在这篇文章中得到了这个结果:

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);
    }
}       
}

【讨论】:

【解决方案2】:

还有一个选项可以像这样使用Apache Codec 来做到这一点

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

【讨论】:

    猜你喜欢
    • 2011-12-08
    • 2021-06-19
    • 2015-12-18
    • 1970-01-01
    • 2012-04-14
    • 1970-01-01
    • 2017-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多