Jethro Hazelhurst
Jethro Hazelhurst

Reputation: 3285

Laravel make unique 16 character hash

I want to make a completely unique hash that is 16 characters long to make a public link for certain private blog posts. So they can be accessed at:

https://website.com/read/ASDFGHJ9827DYCO9

In Laravel there is a helper function that goes

\Hash::make($request->password);

It makes a hash like this:

$2y$10$kouytAixb/Yp5gpH7QqL6et/P.fW.qElsGkMncVM.1/29waEqeqjy

The trouble is that I want to make a hash that only uses letters and numbers and is 16 characters long and is absolutely unique.

Upvotes: 2

Views: 7517

Answers (3)

hossein
hossein

Reputation: 313

Here's two option. Not exactly 16 characters.

  1. Generate random number with php hash function. echo hash('ripemd128', 'some random input'); // echo's hex represented 32byte of data
  2. Encrypt some content, For example id of the page. With symmetric encryption a key will be the unlock for that data. Uniqueness is not important anymore, How can it not be....

Explained in php doc, http://php.net/manual/en/function.openssl-encrypt.php

//$key should have been previously generated in a cryptographically safe way, like openssl_random_pseudo_bytes
$plaintext = "message to be encrypted";
$cipher = "aes-128-gcm";
if (in_array($cipher, openssl_get_cipher_methods()))
{
    $ivlen = openssl_cipher_iv_length($cipher);
    $iv = openssl_random_pseudo_bytes($ivlen);
    $ciphertext = openssl_encrypt($plaintext, $cipher, $key, $options=0, $iv, $tag);
    //store $cipher, $iv, and $tag for decryption later
    $original_plaintext = openssl_decrypt($ciphertext, $cipher, $key, $options=0, $iv, $tag);
    echo $original_plaintext."\n";
}

You can look for list of ciphers with this method, http://php.net/manual/en/function.openssl-get-cipher-methods.php

Upvotes: 1

Felipe Valdes
Felipe Valdes

Reputation: 2217

John Elmore's answer is correct, additionally, Hashing a number makes the value vulnerable to rainbow table attacks, so I would add some "salt" before the actual id, that is hard to guess, so that the rainbow tables are useless, ideally, of length 20 or more:

md5(salt . $model->id)

HTH

Upvotes: 2

John Ellmore
John Ellmore

Reputation: 2229

If it doesn't need to be secure (i.e. you don't care if someone can reverse it to get the original value), just md5() it. That'll return a 16-character hexadecimal string which is reasonably-well distributed.

md5($model->id);

Upvotes: 3

Related Questions