From: Niklas Frykholm Date: 2001-11-13T20:16:17+09:00 Subject: [ruby-talk:25003] Re: Mapping sequential strings to random strings: How would you do this? [Niklas Frykholm] > require 'md5' > secret = 'aljfaweru923jfjkasfljas' > > MD5.md5('doc001.html' + secret).hexdigest + '.html' > > Replace the value of secret with some random string known only to you. > It fulfills 1, 2, 3 and 4. (Well it doesn't fulfill 2 in theory, but > collisions are extremely rare. In fact, if you would find a collision, > you would have 'broken' MD5. You could publish it and become famous. ;) [Hal E. Fulton] > Now, I wonder if there is a way to make the strings shorter? ;) Well that was not in the requirements ;) You can shorten the output from MD5 but it will increase the probability of collisions. For example if you have 1000 documents and use 8 characters from MD5 you have a collision probability of approximately 2/1000. Or in general, for m documents and n characters # Approximate, only valid when m*m << 2.0**(4*n) def coll(m,n) (m*m)/(2.0**(4*n)) end But you can eliminate collisions entirely by prepending a document identifier (such as 001) to each name. Then the hash part will just make the name hard to guess. With four characters in that part, it will take on average 32000 attempts to guess it. Perhaps that is OK. name = id + MD5.md5(id + secret).hexdigest[0,4] + '.html' And if you want to make it even shorter you could recode the id and the hash in Base64 ;) // Niklas