Making a short URL similar to TinyURL.com

前端 未结 5 1402
攒了一身酷
攒了一身酷 2020-12-14 04:39

I\'m building a new web app that has a requirement to generate an internal short URL to be used in the future for users to easily get back to a specific page which has a ver

5条回答
  •  旧时难觅i
    2020-12-14 05:30

    They use base 36 encoding, and you can make your app more robust by using base 64.

    Here's what I'd try in Python (I do see your language tags, forgive me):

    #!/usr/bin/python
    
    from base64 import b64encode
    from hashlib import sha1
    
    for i in range(5):
        salted_int = "%s" % i
        print b64encode(sha1(salted_int).hexdigest())[:6]
    

    Outputs:

    NTUwMz
    ZTVmZD
    OGEzNm
    Njc2MT
    YzVkNj
    

    So you can autoincrement an integer and feed it to some kind of function like this, and end up with a good chance of a random group of strings. See also my answer to this question. Some base64 implementations have the potential to emit a slash / or a plus sign +, and therefore you should keep an eye out for these in your implementation as they're dangerous in URLs.

    Hashes are really flexible and prevent your users from guessing the next URL (if this is important to you).

提交回复
热议问题