Question

I'm working on a project where I need to use some hash function to make a hash string. This hash string should be unique consists of 6 to 13 characters (fixed length).

I use a database to store data, so for each record, I have a unique ID. I want to use this unique ID to make a hash string ( to achieve uniqueness of resulted hash string).

I need this hash string to consists of only valid characters ( 0-9 a-z A-Z).

Which hash function should I use to achieve this goal? How can I generate such hash strings?

Added Later: I want to generate this string and pass it to user, so he can come back later to edit the entry. any other idea is acceptable.

Was it helpful?

Solution

Use crypt:

$hash = crypt("somevaluetohash", $uniqueid);

The unique id is a salt so you can generate different values depending on the id. So if one user had a password of "somevaluetohash" and another user had the same, the ending hash wouldn't be the same.

OTHER TIPS

<?php
  $id;
  $hash_full = md5($id); //hash('sha256', $id);
  $hash_cropped = substr($hash_full, 0, 6);
?>

Use hash() for other hashing algorithms.

But what do you need this hashes for? To me, it doesn't make a lot of sense to generate a hash from the ID, couldn't you just use the ID instead?

Does it really need to be a cryptographic checksum? Or is a simpler checksum suitable? Is the database-provided primary key itself not suitable?

You've got lots of options, from the simplest crc32 to most-advanced sha512.

But if you're doing this for some specific application (such as filesystem hashing, or finding nearby objects using some metrics), then you're going to have to specify more of your problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top