产生短散列的散列函数? [英] Hash function that produces short hashes?
问题描述
有没有一种加密方法可以采用任意长度的字符串并生成小于 10 个字符的散列?我想根据消息内容而不是随机生成合理唯一的 ID.
Is there a way of encryption that can take a string of any length and produce a sub-10-character hash? I want to produce reasonably unique ID's but based on message contents, rather than randomly.
不过,如果不可能使用任意长度的字符串,我可以将消息限制为整数值.但是,在这种情况下,两个连续整数的哈希值不能相似.
I can live with constraining the messages to integer values, though, if arbitrary-length strings are impossible. However, the hash must not be similar for two consecutive integers, in that case.
推荐答案
您可以使用任何常用的哈希算法(例如 SHA-1),这会为您提供比您需要的稍长的结果.只需将结果截断为所需的长度,这可能就足够了.
You can use any commonly available hash algorithm (eg. SHA-1), which will give you a slightly longer result than what you need. Simply truncate the result to the desired length, which may be good enough.
例如,在 Python 中:
For example, in Python:
>>> import hashlib
>>> hash = hashlib.sha1("my message".encode("UTF-8")).hexdigest()
>>> hash
'104ab42f1193c336aa2cf08a2c946d5c6fd0fcdb'
>>> hash[:10]
'104ab42f11'
这篇关于产生短散列的散列函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!