0

How do i randomly generate an alpha numeric string in java.

My session Id string is of the format

b03c0-000-5h6-7645-000000000 

I want to randomly generate only the 4th chunk of it (b03c0-000-5h6-****-000000000). retaining all the other numbers same.

Farvardin
  • 5,336
  • 5
  • 33
  • 54

4 Answers4

2

Apache Commons RandomStringUtils

"b03c0-000-5h6-"+RandomStringUtils.randomAlphanumeric(4)+"-000000000";
Sorter
  • 9,704
  • 6
  • 64
  • 74
0

Try this.

private static final String CONST_ALPHA_NUM ="0123456789abcdef";

public static String getAlphaNumeric(int len) {
    StringBuffer sb = new StringBuffer(len);
    for (int i=0; i<len; i++) {
        int ndx = (int)(Math.random()*CONST_ALPHA_NUM.length());
        sb.append(CONST_ALPHA_NUM.charAt(ndx));
    }
    return sb.toString();
    }

System.out.println("b03c0-000-5h6-" + getAlphaNumeric(4) +"-000000000");
Arjit
  • 3,290
  • 1
  • 17
  • 18
0
import java.util.UUID;    
String uuid = UUID.randomUUID().toString();
String sessionId = "b03c0-000-5h6-" + uuid.substring(0,4) + "-000000000";

to be more random:

String uuid = UUID.randomUUID().toString().replaceAll("-", "");
int n = (int) (Math.random() * 28);
String sessionId = "b03c0-000-5h6-" + uuid.substring(n,n+4) + "-000000000";
Farvardin
  • 5,336
  • 5
  • 33
  • 54
0

If security is important (as I think it is with session identifiers), then I'd suggest using Java's SecureRandom. You can easily get a SecureRandom number with BigInteger:

BigInteger bI = new BigInteger(256, new java.security.SecureRandom())
heikkim
  • 2,955
  • 2
  • 24
  • 34