Coupon code generation

后端 未结 5 839
悲&欢浪女
悲&欢浪女 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 09:09

    What you want is called Format-preserving encryption.

    Without loss of generality, by encoding in base 36 we can assume that we are talking about integers in 0..M-1 rather than strings of symbols. M should probably be a power of 2.

    After choosing a secret key and specifying M, FPE gives you a pseudo-random permutation of 0..M-1 encrypt along with its inverse decrypt.

    string GenerateCoupon(int n) {
        Debug.Assert(0 <= n && n < N);
        return Base36.Encode(encrypt(n));
    }
    
    boolean IsCoupon(string code) {
        return decrypt(Base36.Decode(code)) < N;
    }
    

    If your FPE is secure, this scheme is secure: no attacker can generate other coupon codes with probability higher than O(N/M) given knowledge of arbitrarily many coupons, even if he manages to guess the number associated with each coupon that he knows.

    This is still a relatively new field, so there are few implementations of such encryption schemes. This crypto.SE question only mentions Botan, a C++ library with Perl/Python bindings, but not C#.

    Word of caution: in addition to the fact that there are no well-accepted standards for FPE yet, you must consider the possibility of a bug in the implementation. If there is a lot of money on the line, you need to weigh that risk against the relatively small benefit of avoiding a database.

提交回复
热议问题