How to generate a random alpha-numeric string

前端 未结 30 2435
忘掉有多难
忘掉有多难 2020-11-21 05:38

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 identifie

相关标签:
30条回答
  • 2020-11-21 06:10

    You can use the UUID class with its getLeastSignificantBits() message to get 64 bit of random data, and then convert it to a radix 36 number (i.e. a string consisting of 0-9,A-Z):

    Long.toString(Math.abs( UUID.randomUUID().getLeastSignificantBits(), 36));
    

    This yields a string up to 13 characters long. We use Math.abs() to make sure there isn't a minus sign sneaking in.

    0 讨论(0)
  • 2020-11-21 06:11

    If you're happy to use Apache classes, you could use org.apache.commons.text.RandomStringGenerator (Apache Commons Text).

    Example:

    RandomStringGenerator randomStringGenerator =
            new RandomStringGenerator.Builder()
                    .withinRange('0', 'z')
                    .filteredBy(CharacterPredicates.LETTERS, CharacterPredicates.DIGITS)
                    .build();
    randomStringGenerator.generate(12); // toUpperCase() if you want
    

    Since Apache Commons Lang 3.6, RandomStringUtils is deprecated.

    0 讨论(0)
  • 2020-11-21 06:11

    Using an Apache Commons library, it can be done in one line:

    import org.apache.commons.lang.RandomStringUtils;
    RandomStringUtils.randomAlphanumeric(64);
    

    Documentation

    0 讨论(0)
  • 2020-11-21 06:12

    You mention "simple", but just in case anyone else is looking for something that meets more stringent security requirements, you might want to take a look at jpwgen. jpwgen is modeled after pwgen in Unix, and is very configurable.

    0 讨论(0)
  • 2020-11-21 06:13

    I'm using a library from Apache Commons to generate an alphanumeric string:

    import org.apache.commons.lang3.RandomStringUtils;
    
    String keyLength = 20;
    RandomStringUtils.randomAlphanumeric(keylength);
    

    It's fast and simple!

    0 讨论(0)
  • 2020-11-21 06:13

    I think this is the smallest solution here, or nearly one of the smallest:

     public String generateRandomString(int length) {
        String randomString = "";
    
        final char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567890".toCharArray();
        final Random random = new Random();
        for (int i = 0; i < length; i++) {
            randomString = randomString + chars[random.nextInt(chars.length)];
        }
    
        return randomString;
    }
    

    The code works just fine. If you are using this method, I recommend you to use more than 10 characters. A collision happens at 5 characters / 30362 iterations. This took 9 seconds.

    0 讨论(0)
提交回复
热议问题