cre*_*gox 5 python hash checksum cryptography unique-key
我有很多很多文件要上传到服务器,我只想要一种方法来避免重复.
因此,从一个大字符串生成一个唯一的小键值似乎是校验和要做的事情,并且散列看起来就像是它的演变.
所以我打算使用hash md5来做到这一点.但后来我在某处读到"MD5并不是唯一的密钥",我觉得这很奇怪.
这样做的正确方法是什么?
编辑:顺便说一句,我采取了两个 来源来实现以下目标,这就是我目前正在做的事情,并且它的工作正常,使用Python 2.5:
import hashlib
def md5_from_file (fileName, block_size=2**14):
md5 = hashlib.md5()
f = open(fileName)
while True:
data = f.read(block_size)
if not data:
break
md5.update(data)
f.close()
return md5.hexdigest()
Run Code Online (Sandbox Code Playgroud)
坚持使用MD5是一个好主意.只是为了确保我将文件长度或块数附加到文件哈希表中.
是的,您可能会遇到两个具有相同MD5哈希值的文件,但这种情况不太可能(如果您的文件大小合适).因此,向哈希添加块的数量可以帮助您减少这一点,因为现在您必须找到具有相同MD5的两个相同大小的文件.
# This is the algorithm you described, but also returns the number of chunks.
new_file_hash, nchunks = hash_for_tile(new_file)
store_file(new_file, nchunks, hash)
def store_file(file, nchunks, hash):
"" Tells you whether there is another file with the same contents already, by
making a table lookup ""
# This can be a DB lookup or some way to obtain your hash map
big_table = ObtainTable()
# Two level lookup table might help performance
# Will vary on the number of entries and nature of big_table
if nchunks in big_table:
if hash in big_table[hash]:
raise DuplicateFileException,\
'File is dup with %s' big_table[nchunks][lookup_hash]
else:
big_table[nchunks] = {}
big_table[nchunks].update({
hash: file.filename
})
file.save() # or something
Run Code Online (Sandbox Code Playgroud)
为了减少这种可能性,请切换到SHA1并使用相同的方法.如果性能不是问题,甚至可以使用两者(连接).
当然,请记住,这只适用于二进制级别的重复文件,而不是"相同"但具有不同签名的图像,声音,视频.
| 归档时间: |
|
| 查看次数: |
5834 次 |
| 最近记录: |