生成随机字符串的工具类
2016-06-13 21:43
183 查看
这个类用来生成指定长度的随机字符串
import java.security.SecureRandom; import java.util.Random; /** * Utility that generates a random-value ASCII string. * * @author Ryan Heaton * @author Dave Syer */ public class RandomValueStringGenerator { private static final char[] DEFAULT_CODEC = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" .toCharArray(); private Random random = new SecureRandom(); private int length; /** * Create a generator with the default length (6). */ public RandomValueStringGenerator() { this(6); } /** * Create a generator of random strings of the length provided * * @param length the length of the strings generated */ public RandomValueStringGenerator(int length) { this.length = length; } public String generate() { byte[] verifierBytes = new byte[length]; random.nextBytes(verifierBytes); return getAuthorizationCodeString(verifierBytes); } /** * Convert these random bytes to a verifier string. The length of the byte array can be * {@link #setLength(int) configured}. The default implementation mods the bytes to fit into the * ASCII letters 1-9, A-Z, a-z . * * @param verifierBytes The bytes. * @return The string. */ protected String getAuthorizationCodeString(byte[] verifierBytes) { char[] chars = new char[verifierBytes.length]; for (int i = 0; i < verifierBytes.length; i++) { chars[i] = DEFAULT_CODEC[((verifierBytes[i] & 0xFF) % DEFAULT_CODEC.length)]; } return new String(chars); } /** * The random value generator used to create token secrets. * * @param random The random value generator used to create token secrets. */ public void setRandom(Random random) { this.random = random; } /** * The length of string to generate. * * @param length the length to set */ public void setLength(int length) { this.length = length; } }
相关文章推荐
- 生成随机字符串的工具类
- JAVA工具类(10)--- 随机生成字符串工具类randomUtil
- Java工具类_随机生成任意长度的字符串【密码、验证码】
- Excel生成随机字符串(数字大小写混合)
- python随机生成字符串
- 随机字符串生成图片 PHP代码
- DELPHI生成随机字符串
- PHP随机字符串生成代码(包括大小写字母)
- DES加密深度优化——随机生成加密字符串
- php 生成随机字符串
- js随机生成字母数字组合的字符串 随机动画数字
- php随机生成字符串
- C#生成随机字符串
- 【RFS】【robotframework_1】生成随机数字和随机字符串
- Linux生成随机字符串
- php开发笔记(七)用数组函数实现生成随机字符串
- C#随机生成不重复字符串
- python 随机生成字符串
- 字符串去除空格回车以及随机生成中英文字符串
- [C#]生成一串包含字符和数字的随机字符串的方法