Методы расчета хеша SHA-1 файла с примерами кода

Чтобы вычислить хэш SHA-1 файла на различных языках программирования, вот несколько примеров:

  1. Python:
import hashlib
def calculate_sha1(file_path):
    sha1_hash = hashlib.sha1()
    with open(file_path, 'rb') as file:
        for chunk in iter(lambda: file.read(4096), b''):
            sha1_hash.update(chunk)
    return sha1_hash.hexdigest()
file_path = 'path/to/file8.txt'
sha1_hash = calculate_sha1(file_path)
print("SHA-1 hash:", sha1_hash)
  1. Java:
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class SHA1HashCalculator {
    public static String calculateSHA1(String filePath) throws NoSuchAlgorithmException, IOException {
        MessageDigest sha1Digest = MessageDigest.getInstance("SHA-1");
        try (FileInputStream fileInputStream = new FileInputStream(filePath)) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                sha1Digest.update(buffer, 0, bytesRead);
            }
        }
        byte[] hashBytes = sha1Digest.digest();
        StringBuilder hexString = new StringBuilder();
        for (byte hashByte : hashBytes) {
            String hex = Integer.toHexString(0xff & hashByte);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }
    public static void main(String[] args) {
        String filePath = "path/to/file8.txt";
        try {
            String sha1Hash = calculateSHA1(filePath);
            System.out.println("SHA-1 hash: " + sha1Hash);
        } catch (NoSuchAlgorithmException | IOException e) {
            e.printStackTrace();
        }
    }
}
  1. C#:
using System;
using System.IO;
using System.Security.Cryptography;
public class SHA1HashCalculator
{
    public static string CalculateSHA1(string filePath)
    {
        using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
        {
            using (SHA1Managed sha1 = new SHA1Managed())
            {
                byte[] hash = sha1.ComputeHash(fileStream);
                return BitConverter.ToString(hash).Replace("-", string.Empty).ToLowerInvariant();
            }
        }
    }
    public static void Main(string[] args)
    {
        string filePath = "path/to/file8.txt";
        string sha1Hash = CalculateSHA1(filePath);
        Console.WriteLine("SHA-1 hash: " + sha1Hash);
    }
}