views:

410

answers:

2

I am writing a message transfer program between multiple clients and server.

I want to generate a unique message ID for every message. It should be generated by the server and returned to the client.

For message transfer, I am using a hash data structure, for example:

{
api => POST,
username => sganesh,
pass => "pass",
message => "hai",
time => "current_time",
}

I want to generate a unique ID using this hash.

I have tried several approaches, MD5 and freeze but these give unreadable IDs. I want some meaningful or readable unique IDs.

I have thought we can use microseconds to differentiate between the IDs but here the problem is multiple clients.

In any situation the IDs should be unique.

Can anyone help me out of this problem?

Thanks in advance.

+6  A: 

I suspect you don't want to do what you are asking, but you can do it.

  • Take the hash key/values and flatten them to an array @foo = (%foo).

  • MD5 the array to get an ID code - use md5_base64(@foo) if you want it to be 7bit (human readable).

  • Remember that hashes are not ordered, so you need sort @foo the array if you want it to be repeatable.

In code, something like:

use Digest::MD5 qw(md5_base64);

my $foo = {
    api => POST,
    username => sganesh,
    pass => "pass",
    message => "hai",
    time => "current_time",
};

my $id = md5_base64(sort %$foo); # in my case eRR9QzGN1n+nIl1TDmclEA

To be honest, I think you are better off generating a unique random ID (a token) and giving it to the client to return to you, but then from your question, I don't know your motivation.

Gavin Brock
Excellent. But If the length of the id is less I would be very happy.Is there any way to reduce its length.
sganesh
It's up to how 'unique' you want your 'unique' ID to be. A 128bit MD5 has only about 340,282,366,920,938,463,463,374,607,431,768,211,000 (2^128) combinations. If that still seems too many, just use the first character of the ID with 128 combinations (2^7). Or maybe some middle ground ;-)
Gavin Brock
(And before some pedant corrects me, I know that truncating an MD5 is not a good idea because the distribution may not be even)
Gavin Brock
There's a problem with this, athough it might not matter for the application. Another hash that just happens to have the same data can give you the same MD5, even if it's meant to be a completely separate record.
brian d foy
yeah. I know that we can get a part from an id returned by MD5 sometimes that may not be unique. That's why I asked any other way to reduce that length. But any way thanks Gavin Brock. I am very much satisfied by your answer.
sganesh
+5  A: 

This sounds like a job for Data::UUID.

Furthermore, the unique ID is for a computer. You can abstract that anyway that you like for the humans. :)

brian d foy