1

I have two integers from 0 to infinity (in practice probably less than 1 million, but don't want to have any limitation). I want to encode the two integers into a lowercase alphanumeric string (which may contain a dash, but shouldn't be just numbers). Also I want the strings to be somewhat random (i.e. don't want to always prefix every int with "a" for example). The most important requirement is that I need to be able to easily decode this alphanumeric string.

I would normally just use md5 hashing but it doesn't work for this case as I can't go back from md5 to the original integers. I also considered Base64 but it doesn't work because strings may include uppercase.

Is there a known hashing algorithm that satisfies these requirements?

Stefan D
  • 1,229
  • 2
  • 15
  • 29
  • 2
    What about Base-32? – Nico Schertler Aug 25 '16 at 02:09
  • 1
    It wouldn't be a hashing algorithm if it's reversable, just an encoding algorithm, to be pedantic. – Jacob Aug 25 '16 at 02:12
  • When you say "somewhat random," what do you mean? Random as in unpredictable or random as in highly distributed for sequential values? – Jacob Aug 25 '16 at 02:21
  • You may want to look at http://stackoverflow.com/questions/8554286/obfuscating-an-id for ideas for obfuscating your value, then after it's obfuscated, you can just encode it with something simple like Base-32. – Jacob Aug 25 '16 at 02:42
  • Base-32 looks like what I need. Thank you. – Stefan D Aug 25 '16 at 03:12

1 Answers1

1

If you're just looking to change the integer's base

Instead of base64 you can use base 16 (aka hexadecimal):

>>> hex(1234)[2:]
'4d2'
>>> int('4d2', 16)
1234

or base32:

>>> b32_encode(1234)
b'atja===='
>>> b32_decode(b'atja====')
1234

If you're looking to obscure the integer

The simplest method is to multiple the integer by some number and then xor with some greater, randomized key:

>>> key = 0xFa907fA06 # The result of punching my keyboard.
>>> number = 15485863
>>> obscured = (1234 * number) ^ key
50902290680
>>> hex(obscured)
'bda0350f8'
>>> (50902290680 ^ key) / number
1234

Wanting more robust obfuscation than that requires a tad bit more research, in which case this similar question may be a good place to start.

Community
  • 1
  • 1
Pyonsuke
  • 76
  • 3
  • Thanks, in fact I found a library that does just what I need: https://www.npmjs.com/package/hashids – Stefan D Aug 25 '16 at 03:57