Подтвердить что ты не робот

Java: Как создать SHA-1 для файла?

Каков наилучший способ создания SHA-1 для очень большого файла в чистом Java6? Как реализовать этот метод:

public abstract String createSha1(java.io.File file);
4b9b3361

Ответ 1

Используйте класс MessageDigest и укажите данные по частям. В приведенном ниже примере игнорируются детали, такие как поворот байт [] в строку и закрытие файла, но должны дать вам общую идею.

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

Ответ 2

Операция попросила функцию вернуть строку 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());
    }
}