How to generate a random alpha-numeric string

前端 未结 30 2434
忘掉有多难
忘掉有多难 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:02

    Using Dollar should be as simple as:

    // "0123456789" + "ABCDE...Z"
    String validCharacters = $('0', '9').join() + $('A', 'Z').join();
    
    String randomString(int length) {
        return $(validCharacters).shuffle().slice(length).toString();
    }
    
    @Test
    public void buildFiveRandomStrings() {
        for (int i : $(5)) {
            System.out.println(randomString(12));
        }
    }
    

    It outputs something like this:

    DKL1SBH9UJWC
    JH7P0IT21EA5
    5DTI72EO6SFU
    HQUMJTEBNF7Y
    1HCR6SKYWGT7
    
    0 讨论(0)
  • 2020-11-21 06:02
    1. Change String characters as per as your requirements.

    2. String is immutable. Here StringBuilder.append is more efficient than string concatenation.


    public static String getRandomString(int length) {
        final String characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+";
        StringBuilder result = new StringBuilder();
    
        while(length > 0) {
            Random rand = new Random();
            result.append(characters.charAt(rand.nextInt(characters.length())));
            length--;
        }
        return result.toString();
    }
    
    0 讨论(0)
  • 2020-11-21 06:02
    import java.util.Date;
    import java.util.Random;
    
    public class RandomGenerator {
    
      private static Random random = new Random((new Date()).getTime());
    
        public static String generateRandomString(int length) {
          char[] values = {'a','b','c','d','e','f','g','h','i','j',
                   'k','l','m','n','o','p','q','r','s','t',
                   'u','v','w','x','y','z','0','1','2','3',
                   '4','5','6','7','8','9'};
    
          String out = "";
    
          for (int i=0;i<length;i++) {
              int idx=random.nextInt(values.length);
              out += values[idx];
          }
          return out;
        }
    }
    
    0 讨论(0)
  • 2020-11-21 06:03

    Using UUIDs is insecure, because parts of the UUID aren't random at all. The procedure of erickson is very neat, but it does not create strings of the same length. The following snippet should be sufficient:

    /*
     * The random generator used by this class to create random keys.
     * In a holder class to defer initialization until needed.
     */
    private static class RandomHolder {
        static final Random random = new SecureRandom();
        public static String randomKey(int length) {
            return String.format("%"+length+"s", new BigInteger(length*5/*base 32,2^5*/, random)
                .toString(32)).replace('\u0020', '0');
        }
    }
    

    Why choose 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 range 0 to (2^numBits - 1). Unfortunately 35 is not a number which can be received by 2^numBits - 1.

    So we have two options: Either go with 2^5-1=31 or 2^6-1=63. If we would choose 2^6 we would get a lot of "unnecessary" / "longer" numbers. Therefore 2^5 is the better option, even if we lose four characters (w-z). To now generate a string of a certain length, we can simply use a 2^(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 its required length prepending zeros.

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

    You can use an Apache Commons library for this, RandomStringUtils:

    RandomStringUtils.randomAlphanumeric(20).toUpperCase();
    
    0 讨论(0)
  • 2020-11-21 06:04

    An alternative in Java 8 is:

    static final Random random = new Random(); // Or SecureRandom
    static final int startChar = (int) '!';
    static final int endChar = (int) '~';
    
    static String randomString(final int maxLength) {
      final int length = random.nextInt(maxLength + 1);
      return random.ints(length, startChar, endChar + 1)
            .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
            .toString();
    }
    
    0 讨论(0)
提交回复
热议问题