Hash function to produce a code of 30 chars?

随声附和 提交于 2021-02-07 03:54:07

问题


I need to hash a message into a string of 30 chars. What's the best and most secure hash function for this usage?


回答1:


Thirty characters (bytes) is 240 bits.

If you can't move the goal-post to allow 32 characters, then you will probably end up using SHA-1, which generates 160-bits or 20 bytes. When Base-64 encoded, that will be 28 characters. If you use a hex-encoding, it will be 40 characters, which is nominally out of range. With 32 characters, you could use SHA-256, but Base-64 encoding would increase that size (to 44 characters) and hex-encoding increases the size to 64 characters.

If you must use hex-encoding and can go to 32 bytes, then MD5 - which generates 128 bits - could be used, though it is not recommended for any new systems. With Base-64 encoding, MD5 uses 24 characters. Otherwise, you are using very minimally secure algorithms - not recommended at all.




回答2:


Just use SHA1 and trim to 30 characters.

import hashlib
hash = hashlib.sha1("your message").hexdigest()[:30]

It's been proven that cutting characters off a cryptographically secure hash function such as SHA1 has negligible effects on its security (can't find the reference now though)



来源:https://stackoverflow.com/questions/3536617/hash-function-to-produce-a-code-of-30-chars

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!