Symmetric algorithm for converting integer ID to String

I want to enter a short uniq string identifier using the integer from the MySQL table field (question_id) with Auto Incr.

An example . When the user points to www.something.com/SjBWY → php, you will get an entry with id = 23511;

I want to hide information about the number of questions and enter question_code, which will be displayed from 1 to 1 on question_id using some kind of translation algorithm. I do not want to store question_code in the database, I believe that the MySQL developers are smarter than me and have created a reliable mechanism for generating uniq numbers.

Naive approach: ( http://ideone.com/rK4hzx )

$num = 11231; while($num > 0) { $v = ord( $num % 10); $v += 25; echo chr($v); $num = round($num / 10); } // JLKJJ $result = array_reverse(str_split('JLKJJ')); foreach ($result as $single) { echo chr(ord( $single)-25); } // 11231 

Question: Could you offer the best solutions?

The naive weakness of the past:

  • I want to use small and large letters
  • I want to limit the string length to 5 as much as possible.
  • The generated line should not have an obvious sequence. The value 11 should be so far from 12.

EDIT The algorithm should be symmetric, I can translate Int-> String and String-> Int. MD5 and other hash algorithms is only one way, I cannot translate from String-> Int

+4
source share
3 answers
Finally, I found what I was looking for. He called: http://www.hashids.org/ has versions for php, java, nodejs, ruby, .net, etc.

Hashids was designed for use in URL shortening, account validation, or the creation of private pages (via abstraction). Instead of showing items as 1, 2 or 3, you can show them as b9iLXiAa, EATedTBy and Aaco9cy5. Hashes depend on your salt value.

+4
source

Hashing is not a good option due to a possible collision. What you need for bijective transformation.

For example, you can encrypt the identifier ...

Optional, base64 encodes the resulting bit string or something like that using 6-bit chunks and a character map (for example, [a-zA-Z0-9 _-]).

Whatever you do, make sure you can easily do the inverse transform.

+1
source

why not take the uniq string id, convert it to bytes, and then to long / int? To convert back to convert long / int to bytes and then to string ....

0
source

Source: https://habr.com/ru/post/1484036/


All Articles