I've been looking for a simple Java algorithm to generate a pseudo-random alpha-numeric string. In my situation it would be used as a unique session/key identifier that would "likely" be unique over 500K+ generation (my needs don't really require anything much more sophisticated). Ideally, I would be able to specify a length depending on my uniqueness needs. For example, a generated string of length 12 might look something like "AEYGF7K0DM1X"
.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Surprising no-one here has suggested it but:
Easy.
Benefit of this is UUIDs are nice and long and guaranteed to be almost impossible to collide.
Wikipedia has a good explanation of it:
http://en.wikipedia.org/wiki/Universally_unique_identifier#Random_UUID_probability_of_duplicates
The first 4 bits are the version type and 2 for the variant so you get 122 bits of random. So if you want to you can truncate from the end to reduce the size of the UUID. It's not recommended but you still have loads of randomness, enough for your 500k records easy.
In one line:
Using UUIDs is insecure, because parts of the UUID arn't random at all. The procedure of @erickson is very neat, but does not create strings of the same length. The following snippet should be sufficient:
Why choosing
length*5
. Let's assume the simple case of a random string of length 1, so one random character. To get a random character containing all digits 0-9 and characters a-z, we would need a random number between 0 and 35 to get one of each character.BigInteger
provides a constructor to generate a random number, uniformly distributed over the range0 to (2^numBits - 1)
. Unfortunately 35 is no number which can be received by 2^numBits - 1. So we have two options: Either go with2^5-1=31
or2^6-1=63
. If we would choose2^6
we would get a lot of "unnecesarry" / "longer" numbers. Therefore2^5
is the better option, even if we loose 4 characters (w-z). To now generate a string of a certain length, we can simply use a2^(length*numBits)-1
number. The last problem, if we want a string with a certain length, random could generate a small number, so the length is not met, so we have to pad the string to it's required length prepending zeros.Here it is in Java:
Here's a sample run: