猿问

将哈希值生成为数字的 Python 库

我正在寻找一个库,我需要在其中散列一个字符串,该字符串应该是生产者数字而不是字母数字


eg:

Input string: hello world

Salt value: 5467865390

Output value: 9223372036854775808

我搜索了很多库,但这些库生成字母数字作为输出,但我需要纯数字作为输出。


有没有这样的图书馆?虽然只有数字作为输出的问题很可能会发生冲突,但对于我的业务用例来说这很好。


编辑 1: 我还需要控制输出中的位数。我想将值存储在具有数字数据类型的数据库中。所以我需要控制位数以适应数据类型范围内的大小


largeQ
浏览 679回答 2
2回答

红糖糍粑

十六进制哈希码可以解释为(相当大的)数字:import hashlibhex_hash = hashlib.sha1('hello world'.encode('utf-8')).hexdigest()int_hash = int(hex_hash, 16)  # convert hexadecimal to integerprint(hex_hash)print(int_hash)产出'2aae6c35c94fcfb415dbe95f408b9ce91ee846ed'243667368468580896692010249115860146898325751533编辑:如评论中所问,要将数字限制在某个范围内,您可以简单地使用模数运算符。当然,请注意,这会增加发生冲突的可能性。例如,我们可以将“哈希”限制为 0 .. 9,999,999,模数为 10,000,000。limited_hex_hash = hex_hash % 10_000_000print(limited_hex_hash)产出5751533

犯罪嫌疑人X

我认为不需要图书馆。您可以使用hash()python 中的函数简单地完成此操作。InputString="Hello World!!"HashValue=hash(InputString)print(HashValue)print(type(HashValue))输出:8831022758553168752&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;<class 'int'>&nbsp;基于最新编辑的问题解决方案:上述方法是最简单的解决方案,更改每次调用的哈希值将帮助我们防止攻击者篡改我们的应用程序。如果您想关闭随机化,您可以简单地通过分配 PYTHONHASHSEED to zero.有关关闭随机化检查官方文档https://docs.python.org/3.3/using/cmdline.html#cmdoption-R 的信息
随时随地看视频慕课网APP

相关分类

Python
我要回答