Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to create a random hash/string?

What is the best way of generating a hash for the purpose of storing a session? I am looking for a lightweight, portable solution.

like image 472
Eric Gates Avatar asked Feb 19 '10 02:02

Eric Gates


People also ask

How do I create a hash string?

In order to create a unique hash from a specific string, it can be implemented using their own string to hash converting function. It will return the hash equivalent of a string. Also, a library named Crypto can be used to generate various types of hashes like SHA1, MD5, SHA256 and many more.

How do you generate a random hash function?

The numbers a and b should be randomly generated. However, c needs to be a prime number that is slightly larger than the maximum possible value of x. Once those numbers have been chosen, finding hash value h using h = ((a*x)+b) % c is the standard, accepted way to generate hash functions.


1 Answers

bin2hex(mcrypt_create_iv(22, MCRYPT_DEV_URANDOM)); 
  1. mcrypt_create_iv will give you a random sequence of bytes.
  2. bin2hex will convert it to ASCII text

Example output:

d2c63a605ae27c13e43e26fe2c97a36c4556846dd3ef 

Bare in mind that "best" is a relative term. You have a tradeoff to make between security, uniqueness and speed. The above example is good for 99% of the cases, though if you are dealing with a particularly sensitive data, you might want to read about the difference between MCRYPT_DEV_URANDOM and MCRYPT_DEV_RANDOM.

Finally, there is a RandomLib "for generating random numbers and strings of various strengths".

Notice that so far I have assumed that you are looking to generate a random string, which is not the same as deriving a hash from a value. For the latter, refer to password_hash.

like image 51
Gajus Avatar answered Nov 09 '22 21:11

Gajus