生成随机字符串的工具类

这个类用来生成指定长度的随机字符串

 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 }

 

转载于:https://www.cnblogs.com/godlei/p/5582179.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值