algorithm - How to create a hack proof unique code -


i creating bunch of unique codes in order run promotional campaign. campaign run total of 20 million unique items. validity of code 1 year. looking best possible option. can use 0-9 , a-z in code. limits me using 36 unique characters in code. end user need key in unique cd in system , offers. unique code not tied against user or transaction begin with.

one way generate unique code create incremental numbers , convert them base36 unique cd. problem hackable. users can start inserting unqiue cd in incremental fashion , redeem offers not meant them. thinking of introducing kind of randomisation. need suggestions regarding same.

note - limit of max characters in code 8.

use cryptographically strong random number generator generate 40-bit numbers (i.e. sequences of 5-byte random arrays). converting each array base-36 yield sequence of random eight-character codes. run additional check on each code make sure there no duplicates. using hash set on converted strings let perform task in reasonable time.

here example implementation in java:

set<string> codes = new hashset<>(); securerandom rng = new securerandom(); byte[] data = new byte[5]; (int = 0 ; != 100000 ; i++) {     rng.nextbytes(data);     long val = ((long)(data[0] & 0xff))     | (((long)(data[1] & 0xff)) << 8)     | (((long)(data[2] & 0xff)) << 16)     | (((long)(data[3] & 0xff)) << 24)     | (((long)(data[4] & 0xff)) << 32);     string s = long.tostring(val, 36);     codes.add(s); } system.out.println("generated "+codes.size()+" codes."); 

demo.


Comments

Popular posts from this blog

angular - Is it possible to get native element for formControl? -

unity3d - Rotate an object to face an opposite direction -

javascript - Why jQuery Select box change event is now working? -