146

无论如何,我可以在不自己实现任何算法的情况下将随机字符串散列成 8 位数字吗?

4

4 回答 4

203

是的,您可以使用内置hashlib模块或内置hash函数。然后,在散列的整数形式上使用模运算或字符串切片运算去掉最后八位数字:

>>> s = 'she sells sea shells by the sea shore'

>>> # Use hashlib
>>> import hashlib
>>> int(hashlib.sha1(s.encode("utf-8")).hexdigest(), 16) % (10 ** 8)
58097614L

>>> # Use hash()
>>> abs(hash(s)) % (10 ** 8)
82148974
于 2013-04-15T06:17:59.020 回答
133

Raymond 的回答非常适合 python2(不过,您不需要 abs() 也不需要 10 ** 8 左右的括号)。但是,对于 python3,有一些重要的警告。首先,您需要确保传递的是编码字符串。如今,在大多数情况下,回避 sha-1 并改用 sha-256 之类的东西可能会更好。因此,hashlib 方法将是:

>>> import hashlib
>>> s = 'your string'
>>> int(hashlib.sha256(s.encode('utf-8')).hexdigest(), 16) % 10**8
80262417

如果您想改用 hash() 函数,重要的警告是,与 Python 2.x 不同,在 Python 3.x 中,hash() 的结果只会在进程内保持一致,而不是跨 python 调用。看这里:

$ python -V
Python 2.7.5
$ python -c 'print(hash("foo"))'
-4177197833195190597
$ python -c 'print(hash("foo"))'
-4177197833195190597

$ python3 -V
Python 3.4.2
$ python3 -c 'print(hash("foo"))'
5790391865899772265
$ python3 -c 'print(hash("foo"))'
-8152690834165248934

这意味着建议使用基于 hash() 的解决方案,可以将其缩短为:

hash(s) % 10**8

只会在给定的脚本运行中返回相同的值:

#Python 2:
$ python2 -c 's="your string"; print(hash(s) % 10**8)'
52304543
$ python2 -c 's="your string"; print(hash(s) % 10**8)'
52304543

#Python 3:
$ python3 -c 's="your string"; print(hash(s) % 10**8)'
12954124
$ python3 -c 's="your string"; print(hash(s) % 10**8)'
32065451

因此,根据这在您的应用程序中是否重要(在我的应用程序中确实如此),您可能希望坚持使用基于 hashlib 的方法。

于 2017-02-07T11:57:54.957 回答
9

只是为了完成 JJC 答案,在 python 3.5.3 中,如果您以这种方式使用 hashlib,则行为是正确的:

$ python3 -c '
import hashlib
hash_object = hashlib.sha256(b"Caroline")
hex_dig = hash_object.hexdigest()
print(hex_dig)
'
739061d73d65dcdeb755aa28da4fea16a02b9c99b4c2735f2ebfa016f3e7fded
$ python3 -c '
import hashlib
hash_object = hashlib.sha256(b"Caroline")
hex_dig = hash_object.hexdigest()
print(hex_dig)
'
739061d73d65dcdeb755aa28da4fea16a02b9c99b4c2735f2ebfa016f3e7fded

$ python3 -V
Python 3.5.3
于 2017-11-15T22:02:45.947 回答
-8

我正在分享由@Raymond Hettinger 实现的解决方案的nodejs 实现。

var crypto = require('crypto');
var s = 'she sells sea shells by the sea shore';
console.log(BigInt('0x' + crypto.createHash('sha1').update(s).digest('hex'))%(10n ** 8n));
于 2019-10-28T19:03:17.810 回答