Samuel Fernandes

Total Post:159

Posted by  Samuel Fernandes
Java  String 
 959  View(s)
Rate this:
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".
  1. Mayank Tripathi


    Re: How to generate a random alpha-numeric string?

    Here is code for secure, easy, but a little bit more expensive session identifiers.

    public final class SessionIdentifierGenerator {
      private SecureRandom random = new SecureRandom();
      public String nextSessionId() {
        return new BigInteger(130, random).toString(32);
    This works by choosing 130 bits from a cryptographically secure random bit generator, and encoding them in base-32. 128 bits is considered to be cryptographically strong, but each digit in a base 32 number can encode 5 bits, so 128 is rounded up to the next multiple of 5. This encoding is compact and efficient, with 5 random bits per character. Compare this to a random UUID, which only has 3.4 bits per character in standard layout, and only 122 random bits in total.

    If you allow session identifiers to be easily guessable (too short, flawed random number generator, etc.), attackers can hijack other's sessions. Note that SecureRandom objects are expensive to initialize, so you'll want to keep one around and reuse it.

    Here is alternative code for cheap, insecure random alpha-numeric strings. You can tweak the "symbols" if you want to use more characters.

    public class RandomString {
      private static final char[] symbols;
      static {
        StringBuilder tmp = new StringBuilder();
        for (char ch = '0'; ch <= '9'; ++ch)
        for (char ch = 'a'; ch <= 'z'; ++ch)
        symbols = tmp.toString().toCharArray();
      private final Random random = new Random();
      private final char[] buf;
      public RandomString(int length) {
        if (length < 1)
          throw new IllegalArgumentException("length < 1: " + length);
        buf = new char[length];
      public String nextString() {
        for (int idx = 0; idx < buf.length; ++idx) 
          buf[idx] = symbols[random.nextInt(symbols.length)];
        return new String(buf);

    Java supplies a way of doing this directly. If you don't want the dashes, they are easy to strip out.

    import java.util.UUID;
    String uuid = UUID.randomUUID().toString();
    System.out.println("uuid = " + uuid);



Enter your email address here always to be updated. We promise not to spam!