Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hash function to produce a code of 30 chars?

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

like image 540
cfischer Avatar asked Dec 09 '22 14:12

cfischer


2 Answers

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.

like image 92
Jonathan Leffler Avatar answered Dec 13 '22 12:12

Jonathan Leffler


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)

like image 27
quantumSoup Avatar answered Dec 13 '22 10:12

quantumSoup