views:

55

answers:

3

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.

A: 
<?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?

phant0m
You know, I want to pass this string to user, as a password so he can edit the entry later. I don't cropping a hash string put it in danger of more collisions.
Morteza M.
A: 

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.

Neb
I planned to use it, but it generates some special characters like dot,slash and so on. I want the string to contains only alphanumeric characters.
Morteza M.
You can always make a filter for this. Or you could make a hash with $hash = md5("somevaluetohash".$uniqueid);
Neb
@neb: your idea is good. but can I somehow reduce the length of generated code to 6 or 13 ( not using a simple crop ).
Morteza M.
Maybe check http://stackoverflow.com/questions/959957/php-short-hash ? If you cant find any other method of hashing which has a 6 to 13 length, just use the same method: "somevaluetohash".$uniqueid
Neb
A: 

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.

sarnold