Как обнаружить идентичные файлы, не сравнивая их друг с другом?

StackOverflow https://stackoverflow.com/questions/5016947

Вопрос

Я строю сайт, где пользователи могут загружать контент. Как всегда, я стремлюсь к миру господству, поэтому я хотел бы избежать хранения одного и того же файла дважды. Например, если пользователь пытается загрузить один и тот же файл два раза (переименовав или просто забыв о том, что она сделала в прошлом).

Мой текущий подход - это иметь базу данных, которая отслеживает каждый загруженный файл хранить следующую информацию о каждом файле:

    .
  • Размер файла в байтах
  • md5 сумма содержимого файла
  • sha1 сумма содержимого файла

    , а затем уникальный индекс на этих трех столбцах. Используя два хэши к минимизировать риск ложных срабатываний.

    Итак, мой вопрос действительно: Какова вероятность двух разных («реальных») файлов одного и того же размера, имеющих одинаковые MD5 и Hashes yeak?

    или: Есть ли умнее метод схожих (ООН) сложности?

    (Я понимаю, что вероятность может зависеть от размера файла).

    Спасибо!

Это было полезно?

Решение

The probability of two real-world files of the same size having the same SHA1 hash is zero for all practical purposes. Some weaknesses in SHA1 have been found, but creating a file from a SHA1 hash and a size (1) is incredibly expensive in terms of computing power and (2) produces either garbage or the original file.

Adding MD5 to the mix is total overkill. If you don't trust SHA-1, then a better option is to switch to SHA-2.

If you're really paranoid, try comparing files with identical (size, SHA1) signatures. That will, however, have to read both the files entirely if they are equal.

Другие советы

I believe storing MD5 and SHA1 hashes is adding unnecessary complexity and not good design. I would say storing the tuple of (SHA1, file size) would be by far good enough. Especially if you're starting a new community site, I'd safely use that solution and only create something more clever once it becomes a problem. As the saying goes, premature optimization is the root of all evil, and it's arguable if it'll be `optimizing'.

edit: I did not quantify the odds of you getting a MD5+SHA1 collision. I'd say it's zero. By a crude, back of the envelope calculation, the odds of two different files of arbitrary file sizes having identical (SHA1,MD5) tuple is 2^-288, which is zero as far as I'm concerned. Having to require identical file size reduces that even further.

You can use Broders implementation of the Rabin fingerprinting algorithm. It is faster to compute than sha1 and md5 and it is proven to be collision resistant. However, it is not considered to be safe against malicious attacks, it is possible fot someone to purposefuly alter the file in question sithout changing the fingerprint itself. If you just want to check the similarity of files, it is s pretty good solution.

C# implementation, not tested:

http://www.developpez.net/forums/d863959/dotnet/general-dotnet/contribuez/algorithm-rabin-fingerprint/

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top