M Rajoy
M Rajoy

Reputation: 4084

Generate unique codes based on MAC address

I would like to be able to generate alphanumerical codes (as in discount codes) that are valid for a single Android device, for a limited time each.

That is, I need to find a way to generate unique infinite (or a high number of, at least) codes that are only valid for a single device.

I thought about using the MAC address as the "seed" for my code generation, but I don't know how to generate the codes themselves. Are there any common approaches or solutions to this problem?

PS. I need an algorithm that does not depend on a code database, since my devices might not have connectivity when activating the codes.

Upvotes: 1

Views: 2668

Answers (1)

Joe F
Joe F

Reputation: 652

Essentially what you are looking for is some form of hash function. You could do this by generating any random number as a base. Once you have this, calculate the hash of it (as a string), and also the hash of it concatenated with the mac address of the device. The discount code could then be:

temp = hash(random())
code = concat(temp, hash(concat(mac_address, temp)))

This could then be checked by confirming that the first half of the code can be concatenated onto the mac address and hashed to produce the second half.

valid = hash(concat(mac_address, first_half(code))) == second_half(code)

Alternatively, instead of a random number you could keep track of how many have been requested and use this in place of the random() call. This should* always give you unique codes to process, and you can keep track of which codes have been redeemed on your server.

  • Collisions may occur in the results of the hash function, but the chance of this is very small indeed if you choose carefully.

Obviously, all the above is very generic pseudo-code. I hope this helps.

Some info about hash functions (specifically cryptographic ones, which are what you want for secure things like this):

http://en.wikipedia.org/wiki/Cryptographic_hash_function

Upvotes: 1

Related Questions