liukangdong
2024-08-15 9a9af13c74e98dfdb61afd9cbe56b1b7ec8c3414
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package com.doumee.core.utils;
 
import java.security.SecureRandom;
import java.util.Locale;
import java.util.Objects;
import java.util.Random;
 
public class RandomString {
 
  protected static final String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  protected static final String lower = upper.toLowerCase(Locale.ROOT);
  protected static final String digits = "0123456789";
  protected static final String alphaNumeric = 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, alphaNumeric);
  }
 
  /**
   * Create an alphanumeric strings from a secure generator.
   */
  public RandomString(int length) {
    this(length, new SecureRandom());
  }
 
  /**
   * Create session identifiers.
   */
  public RandomString() {
    this(21);
  }
 
  /**
   * 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);
  }
}