Search code examples
pythonsecuritypromotions

generating promotion code using python


By using python language, what would be a clever / efficient way of generating promotion codes. Like to be used for generating special numbers for discount coupons. like: 1027828-1

Thanks


Solution

  • 1027828-1 is extremely small. An attacker can make a ~million guesses using only a couple lines of code and maybe a few days.

    This is a good way to produce a hard to predict number using python, it works under linux and windows. It is base64'ed for binary safety, depending what you are doing with it you might want to urllib.urlencode() but I would avoid base10 because it doesn't store as much information.

    import os
    import base64
    
    def secure_rand(len=8):
        token=os.urandom(len)
        return base64.b64encode(token)
    
    print(secure_rand())
    

    As a side note this is generating a full byte, which is base256. 256^8 is 18446744073709551616 which should be large enough.

    As it was pointed out base64 isn't a very good token for humans to use. Consider an alternate encoding like url-safe base64 or perhaps humanhash as they would be easier to type in.