How to generate a random alpha-numeric string

前端 未结 30 2433
忘掉有多难
忘掉有多难 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:04
    import java.util.Random;
    
    public class passGen{
        // Version 1.0
        private static final String dCase = "abcdefghijklmnopqrstuvwxyz";
        private static final String uCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        private static final String sChar = "!@#$%^&*";
        private static final String intChar = "0123456789";
        private static Random r = new Random();
        private static StringBuilder pass = new StringBuilder();
    
        public static void main (String[] args) {
            System.out.println ("Generating pass...");
            while (pass.length () != 16){
                int rPick = r.nextInt(4);
                if (rPick == 0){
                    int spot = r.nextInt(26);
                    pass.append(dCase.charAt(spot));
                } else if (rPick == 1) {
                    int spot = r.nextInt(26);
                    pass.append(uCase.charAt(spot));
                } else if (rPick == 2) {
                    int spot = r.nextInt(8);
                    pass.append(sChar.charAt(spot));
                } else {
                    int spot = r.nextInt(10);
                    pass.append(intChar.charAt(spot));
                }
            }
            System.out.println ("Generated Pass: " + pass.toString());
        }
    }
    

    This just adds the password into the string and... yeah, it works well. Check it out... It is very simple; I wrote it.

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

    Java supplies a way of doing this directly. If you don't want the dashes, they are easy to strip out. Just use uuid.replace("-", "")

    import java.util.UUID;
    
    public class randomStringGenerator {
        public static void main(String[] args) {
            System.out.println(generateString());
        }
    
        public static String generateString() {
            String uuid = UUID.randomUUID().toString();
            return "uuid = " + uuid;
        }
    }
    

    Output

    uuid = 2d7428a6-b58c-4008-8575-f05549f16316
    
    0 讨论(0)
  • 2020-11-21 06:06
    static final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    static SecureRandom rnd = new SecureRandom();
    
    String randomString(int len){
       StringBuilder sb = new StringBuilder(len);
       for(int i = 0; i < len; i++)
          sb.append(AB.charAt(rnd.nextInt(AB.length())));
       return sb.toString();
    }
    
    0 讨论(0)
  • 2020-11-21 06:06

    Here it is in Java:

    import static java.lang.Math.round;
    import static java.lang.Math.random;
    import static java.lang.Math.pow;
    import static java.lang.Math.abs;
    import static java.lang.Math.min;
    import static org.apache.commons.lang.StringUtils.leftPad
    
    public class RandomAlphaNum {
      public static String gen(int length) {
        StringBuffer sb = new StringBuffer();
        for (int i = length; i > 0; i -= 12) {
          int n = min(12, abs(i));
          sb.append(leftPad(Long.toString(round(random() * pow(36, n)), 36), n, '0'));
        }
        return sb.toString();
      }
    }
    

    Here's a sample run:

    scala> RandomAlphaNum.gen(42)
    res3: java.lang.String = uja6snx21bswf9t89s00bxssu8g6qlu16ffzqaxxoy
    
    0 讨论(0)
  • 2020-11-21 06:07

    I don't really like any of these answers regarding a "simple" solution :S

    I would go for a simple ;), pure Java, one liner (entropy is based on random string length and the given character set):

    public String randomString(int length, String characterSet) {
        return IntStream.range(0, length).map(i -> new SecureRandom().nextInt(characterSet.length())).mapToObj(randomInt -> characterSet.substring(randomInt, randomInt + 1)).collect(Collectors.joining());
    }
    
    @Test
    public void buildFiveRandomStrings() {
        for (int q = 0; q < 5; q++) {
            System.out.println(randomString(10, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")); // The character set can basically be anything
        }
    }
    

    Or (a bit more readable old way)

    public String randomString(int length, String characterSet) {
        StringBuilder sb = new StringBuilder(); // Consider using StringBuffer if needed
        for (int i = 0; i < length; i++) {
            int randomInt = new SecureRandom().nextInt(characterSet.length());
            sb.append(characterSet.substring(randomInt, randomInt + 1));
        }
        return sb.toString();
    }
    
    @Test
    public void buildFiveRandomStrings() {
        for (int q = 0; q < 5; q++) {
            System.out.println(randomString(10, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")); // The character set can basically be anything
        }
    }
    

    But on the other hand you could also go with UUID which has a pretty good entropy:

    UUID.randomUUID().toString().replace("-", "")
    
    0 讨论(0)
  • 2020-11-21 06:08

    Algorithm

    To generate a random string, concatenate characters drawn randomly from the set of acceptable symbols until the string reaches the desired length.

    Implementation

    Here's some fairly simple and very flexible code for generating random identifiers. Read the information that follows for important application notes.

    public class RandomString {
    
        /**
         * Generate a random string.
         */
        public String nextString() {
            for (int idx = 0; idx < buf.length; ++idx)
                buf[idx] = symbols[random.nextInt(symbols.length)];
            return new String(buf);
        }
    
        public static final String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    
        public static final String lower = upper.toLowerCase(Locale.ROOT);
    
        public static final String digits = "0123456789";
    
        public static final String alphanum = upper + lower + digits;
    
        private final Random random;
    
        private final char[] symbols;
    
        private final char[] buf;
    
        public RandomString(int length, Random random, String symbols) {
            if (length < 1) throw new IllegalArgumentException();
            if (symbols.length() < 2) throw new IllegalArgumentException();
            this.random = Objects.requireNonNull(random);
            this.symbols = symbols.toCharArray();
            this.buf = new char[length];
        }
    
        /**
         * Create an alphanumeric string generator.
         */
        public RandomString(int length, Random random) {
            this(length, random, alphanum);
        }
    
        /**
         * Create an alphanumeric strings from a secure generator.
         */
        public RandomString(int length) {
            this(length, new SecureRandom());
        }
    
        /**
         * Create session identifiers.
         */
        public RandomString() {
            this(21);
        }
    
    }
    

    Usage examples

    Create an insecure generator for 8-character identifiers:

    RandomString gen = new RandomString(8, ThreadLocalRandom.current());
    

    Create a secure generator for session identifiers:

    RandomString session = new RandomString();
    

    Create a generator with easy-to-read codes for printing. The strings are longer than full alphanumeric strings to compensate for using fewer symbols:

    String easy = RandomString.digits + "ACEFGHJKLMNPQRUVWXYabcdefhijkprstuvwx";
    RandomString tickets = new RandomString(23, new SecureRandom(), easy);
    

    Use as session identifiers

    Generating session identifiers that are likely to be unique is not good enough, or you could just use a simple counter. Attackers hijack sessions when predictable identifiers are used.

    There is tension between length and security. Shorter identifiers are easier to guess, because there are fewer possibilities. But longer identifiers consume more storage and bandwidth. A larger set of symbols helps, but might cause encoding problems if identifiers are included in URLs or re-entered by hand.

    The underlying source of randomness, or entropy, for session identifiers should come from a random number generator designed for cryptography. However, initializing these generators can sometimes be computationally expensive or slow, so effort should be made to re-use them when possible.

    Use as object identifiers

    Not every application requires security. Random assignment can be an efficient way for multiple entities to generate identifiers in a shared space without any coordination or partitioning. Coordination can be slow, especially in a clustered or distributed environment, and splitting up a space causes problems when entities end up with shares that are too small or too big.

    Identifiers generated without taking measures to make them unpredictable should be protected by other means if an attacker might be able to view and manipulate them, as happens in most web applications. There should be a separate authorization system that protects objects whose identifier can be guessed by an attacker without access permission.

    Care must be also be taken to use identifiers that are long enough to make collisions unlikely given the anticipated total number of identifiers. This is referred to as "the birthday paradox." The probability of a collision, p, is approximately n2/(2qx), where n is the number of identifiers actually generated, q is the number of distinct symbols in the alphabet, and x is the length of the identifiers. This should be a very small number, like 2‑50 or less.

    Working this out shows that the chance of collision among 500k 15-character identifiers is about 2‑52, which is probably less likely than undetected errors from cosmic rays, etc.

    Comparison with UUIDs

    According to their specification, UUIDs are not designed to be unpredictable, and should not be used as session identifiers.

    UUIDs in their standard format take a lot of space: 36 characters for only 122 bits of entropy. (Not all bits of a "random" UUID are selected randomly.) A randomly chosen alphanumeric string packs more entropy in just 21 characters.

    UUIDs are not flexible; they have a standardized structure and layout. This is their chief virtue as well as their main weakness. When collaborating with an outside party, the standardization offered by UUIDs may be helpful. For purely internal use, they can be inefficient.

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