Coupon code generation

后端 未结 5 837
悲&欢浪女
悲&欢浪女 2020-12-07 08:24

I would like to generate coupon codes , e.g. AYB4ZZ2. However, I would also like to be able to mark the used coupons and limit their global number, let\'s say <

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-07 08:59

    • Choose a cryptographic function c. There are a few requirements on c, but for now let us take SHA1.

    • choose a secret key k.

    Your coupon code generating function could be, for number n:

    • concatenate n and k as "n"+"k" (this is known as salting in password management)
    • compute c("n"+"k")
    • the result of SHA1 is 160bits, encode them (for instance with base64) as an ASCII string
    • if the result is too long (as you said it is the case for SHA1), truncate it to keep only the first 10 letters and name this string s
    • your coupon code is printf "%09d%s" n s, i.e. the concatenation of zero-padded n and the truncated hash s.

    Yes, it is trivial to guess n the number of the coupon code (but see below). But it is hard to generate another valid code.

    Your requirements are satisfied:

    1. To compute the reverse function, just read the first 9 digits of the code
    2. The length is always 19 (9 digits of n, plus 10 letters of hash)
    3. It is unique, since the first 9 digits are unique. The last 10 chars are too, with high probability.
    4. It is not obvious how to generate the hash, even if one guesses that you used SHA1.


    Some comments:

    • If you're worried that reading n is too obvious, you can obfuscate it lightly, like base64 encoding, and alternating in the code the characters of n and s.
    • I am assuming that you won't need more than a billion codes, thus the printing of n on 9 digits, but you can of course adjust the parameters 9 and 10 to your desired coupon code length.
    • SHA1 is just an option, you could use another cryptographic function like private key encryption, but you need to check that this function remains strong when truncated and when the clear text is provided.
    • This is not optimal in code length, but has the advantage of simplicity and widely available libraries.

提交回复
热议问题