Java:如何为文件创建SHA-1?

Wit*_*tek 28 java cryptography sha

在纯Java6中为非常大的文件创建SHA-1的最佳方法是什么?如何实现此方法:

public abstract String createSha1(java.io.File file);
Run Code Online (Sandbox Code Playgroud)

Jef*_*ter 39

MessageDigest逐个使用类和提供数据.下面的示例忽略了将byte []转换为字符串并关闭文件等细节,但应该给出一般的想法.

public byte[] createSha1(File file) throws Exception  {
    MessageDigest digest = MessageDigest.getInstance("SHA-1");
    InputStream fis = new FileInputStream(file);
    int n = 0;
    byte[] buffer = new byte[8192];
    while (n != -1) {
        n = fis.read(buffer);
        if (n > 0) {
            digest.update(buffer, 0, n);
        }
    }
    return digest.digest();
}
Run Code Online (Sandbox Code Playgroud)

  • 应该关闭FIleInputStream,就像在另一个响应中一样 (3认同)
  • DigestInputStream类更容易使用.实际上可能没有,但尝试将其作为替代方案并与此进行比较是很好的. (2认同)
  • @Jeff Foster 你如何确定 `byte[] buffer` 的大小是 `8192`? (2认同)

use*_*795 19

操作系统要求函数返回SHA1的字符串,所以我接受了@jeffs的答案,并将缺少的转换添加到String:

/**
 * Read the file and calculate the SHA-1 checksum
 * 
 * @param file
 *            the file to read
 * @return the hex representation of the SHA-1 using uppercase chars
 * @throws FileNotFoundException
 *             if the file does not exist, is a directory rather than a
 *             regular file, or for some other reason cannot be opened for
 *             reading
 * @throws IOException
 *             if an I/O error occurs
 * @throws NoSuchAlgorithmException
 *             should never happen
 */
private static String calcSHA1(File file) throws FileNotFoundException,
        IOException, NoSuchAlgorithmException {

    MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
    try (InputStream input = new FileInputStream(file)) {

        byte[] buffer = new byte[8192];
        int len = input.read(buffer);

        while (len != -1) {
            sha1.update(buffer, 0, len);
            len = input.read(buffer);
        }

        return new HexBinaryAdapter().marshal(sha1.digest());
    }
}
Run Code Online (Sandbox Code Playgroud)