How to calculate short fixed length, obfuscation ID similar to YouTube (e.g. 2WNrx2jq184)

Each user object in my database has an incremental identifier (1, 2, 3, ...). The URL for viewing the user profile contains the identifier of the user object; e.g. http://www.example.com/users/1 . Thus, everyone can see how many users are on the website, how fast the database is growing, etc. I do not want to send this information.

I would like to convert the incremental identifier to a fixed-length string in Base58 format, so the URL will look like http://www.example.com/users/2WNrx2jq184 Also, I need an inverse function that converts the string back to the original identifier. Reversible function should not be easily reconstructed.

The best Python code I've found for this purpose is https://github.com/JordanReiter/django-id-obfuscator . This is very good, but in some cases it adds a character 0and / or ., which results in strings that are not in Base58, and not a fixed length. (See utils.py lines 24 and 29.)

How can I improve django-id-obfuscator to result in obfuscation of IDs with a fixed length of base58 or how can I create such obfuscation identifiers in Python?

+5
source share
2 answers

If you want to do it right, take your user ID, put it with leading zeros, then encrypt it with something like AES and encode the result with base58. To return the identifier, simply decode, decrypt, and the int()result.

So for encryption:

>>> from Crypto.Cipher import AES
>>> import base64
>>> obj = AES.new('yoursecretkeyABC')
>>> x = base64.encodestring(obj.encrypt("%016d"%1))
>>> x
'tXDxMg1YGb1i0V29yCCBWg==\n'

and decryption

>>> int(obj.decrypt(base64.decodestring(x)))
1

If you can live with weak cryptography, you can also just flash the identifier with the key:

>>> key = [33, 53, 2, 42]
>>> id = "%04d" % 1
>>> x = ''.join([chr(a^ord(b)) for a, b in zip(key, id)])
>>> x
'\x11\x052\x1b'
>>> int(''.join([chr(a^ord(b)) for a, b in zip(key, x)]))
1

, OTP . , , .

+5

, . hashids, :

http://hashids.org

0

All Articles