这个类用来生成指定长度的随机字符串
1 import java.security.SecureRandom; 2 import java.util.Random; 3 4 /** 5 * Utility that generates a random-value ASCII string. 6 * 7 * @author Ryan Heaton 8 * @author Dave Syer 9 */ 10 public class RandomValueStringGenerator { 11 12 private static final char[] DEFAULT_CODEC = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" 13 .toCharArray(); 14 15 private Random random = new SecureRandom(); 16 17 private int length; 18 19 /** 20 * Create a generator with the default length (6). 21 */ 22 public RandomValueStringGenerator() { 23 this(6); 24 } 25 26 /** 27 * Create a generator of random strings of the length provided 28 * 29 * @param length the length of the strings generated 30 */ 31 public RandomValueStringGenerator(int length) { 32 this.length = length; 33 } 34 35 public String generate() { 36 byte[] verifierBytes = new byte[length]; 37 random.nextBytes(verifierBytes); 38 return getAuthorizationCodeString(verifierBytes); 39 } 40 41 /** 42 * Convert these random bytes to a verifier string. The length of the byte array can be 43 * {@link #setLength(int) configured}. The default implementation mods the bytes to fit into the 44 * ASCII letters 1-9, A-Z, a-z . 45 * 46 * @param verifierBytes The bytes. 47 * @return The string. 48 */ 49 protected String getAuthorizationCodeString(byte[] verifierBytes) { 50 char[] chars = new char[verifierBytes.length]; 51 for (int i = 0; i < verifierBytes.length; i++) { 52 chars[i] = DEFAULT_CODEC[((verifierBytes[i] & 0xFF) % DEFAULT_CODEC.length)]; 53 } 54 return new String(chars); 55 } 56 57 /** 58 * The random value generator used to create token secrets. 59 * 60 * @param random The random value generator used to create token secrets. 61 */ 62 public void setRandom(Random random) { 63 this.random = random; 64 } 65 66 /** 67 * The length of string to generate. 68 * 69 * @param length the length to set 70 */ 71 public void setLength(int length) { 72 this.length = length; 73 } 74 75 }