I would like to generate random identifier in java. The identifier should have a fixed size, and the probability of generating the same identifier twice should be very low(The system has about 500 000 users).In addition; the identifier should be so long that it’s unfeasible to “guess it” by a brute force attack.
My approach so far is something along the lines of this:
String alphabet = "0123456789ABCDE....and so on";
int lengthOfAlphabet = 42;
long length = 12;
public String generateIdentifier(){
String identifier = "";
Random random = new Random();
for(int i = 0;i<length;i++){
identifier+= alphabet.charAt(random.nextInt(lengthOfAlphabet));
}
return identifier;
}
I’m enforcing the uniqueness by a constraint in the database. If I hit an identifier that already has been created, I’ll keep generating until I find one that’s not in use.
My assumption is that I can tweak lenghtOfAlpahbet and length to get the properties I’m looking for:
- Rare collisions
- Unfeasible to brute force
- The identifier should be as short as possible, as the users of the system will have to type it.
Is this a good approach? Does anyone have any thoughts on the value of “length”?