Oblicz sumę kontrolną MD5 dla pliku

Używam iTextSharp do odczytu tekstu z pliku PDF. Czasami jednak nie mogę wyodrębnić tekstu, ponieważ plik PDF zawiera tylko obrazy. Codziennie pobieram te same pliki PDF i chcę sprawdzić, czy plik PDF został zmodyfikowany. Jeśli nie można uzyskać tekstu i daty modyfikacji, czy suma kontrolna MD5 jest najbardziej wiarygodnym sposobem na sprawdzenie, czy Plik się zmienił?

Jeśli tak, niektóre próbki kodu byłyby mile widziane, ponieważ nie mam dużego doświadczenia z kryptografia.

Author: CodesInChaos, 2012-05-09

5 answers

To bardzo proste użycie System. Security. Cryptography. MD5 :

using (var md5 = MD5.Create())
{
    using (var stream = File.OpenRead(filename))
    {
        return md5.ComputeHash(stream);
    }
}

(wierzę, żew rzeczywistości implementacja MD5 nie musi być usuwana, ale i tak pewnie bym to zrobił.)

Sposób porównywania wyników zależy od ciebie; możesz przekonwertować tablicę bajtów na przykład base64 lub bezpośrednio porównać bajty. (Należy pamiętać, że tablice nie nadpisują Equals. Korzystanie z base64 jest prostsze, ale nieco mniej wydajne, jeśli naprawdę interesuje mnie tylko porównanie hashów.)

Jeśli chcesz reprezentować hash jako ciąg znaków, możesz przekonwertować go na szesnastkowy za pomocą BitConverter:

static string CalculateMD5(string filename)
{
    using (var md5 = MD5.Create())
    {
        using (var stream = File.OpenRead(filename))
        {
            var hash = md5.ComputeHash(stream);
            return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
        }
    }
}
 619
Author: Jon Skeet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-16 12:52:42

Tak to robię:

using System.IO;
using System.Security.Cryptography;

public string checkMD5(string filename)
{
    using (var md5 = MD5.Create())
    {
        using (var stream = File.OpenRead(filename))
        {
            return Encoding.Default.GetString(md5.ComputeHash(stream));
        }
    }
}
 56
Author: BoliBerrys,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-28 15:27:25

Wiem, że na to pytanie już udzielono odpowiedzi, ale to jest to, czego używam:

using (FileStream fStream = File.OpenRead(filename)) {
    return GetHash<MD5>(fStream)
}

Gdzie GetHash :

public static String GetHash<T>(Stream stream) where T : HashAlgorithm {
    StringBuilder sb = new StringBuilder();

    MethodInfo create = typeof(T).GetMethod("Create", new Type[] {});
    using (T crypt = (T) create.Invoke(null, null)) {
        byte[] hashBytes = crypt.ComputeHash(stream);
        foreach (byte bt in hashBytes) {
            sb.Append(bt.ToString("x2"));
        }
    }
    return sb.ToString();
}

Prawdopodobnie nie jest to najlepszy sposób, ale może być przydatny.

 5
Author: Badaro Jr.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-21 19:16:14

Oto nieco prostsza wersja, którą znalazłem. Odczytuje cały plik za jednym razem i wymaga tylko jednej dyrektywy using.

byte[] ComputeHash(string filePath)
{
    using (var md5 = MD5.Create())
    {
        return md5.ComputeHash(File.ReadAllBytes(filePath));
    }
}
 2
Author: Ashley Davis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-28 15:26:45

Jeśli chcesz obliczyć MD5, aby sprawdzić, czy pasuje do MD5 Bloba platformy Azure, to takie pytanie i odpowiedź mogą być pomocne: Skrót MD5 Bloba przesłanego na platformę Azure nie pasuje do tego samego pliku na maszynie lokalnej

 2
Author: Manfred,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:10:46