利用Random方法生产随机密码。
将字母,数字,符号拆开成可取用的数组,按照密码长度做生成策略, 分别为小写字母占密码长度的1/2,大写字母和数字各占1/4,符号占剩余无法除尽的(最多两个符号)。
然后循环取值,每一次从数组中随机拿取字符,并把这个字符随机放入生产的密码字符串中的某个位置。
public final static String[] LOWER_CASES = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
public final static String[] UPPER_CASES = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
public final static String[] NUMS_LIST = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
public final static String[] SYMBOLS_ARRAY = {"!","~","^","_","*"};
/**
* 生成随机密码
* @param pwd_len 密码长度
* @return 密码的字符串
*/
public static String genRandomPwd(int pwd_len) {
if ( pwd_len < 6 || pwd_len >20 ) {
return "";
}
int lower = pwd_len / 2 ;
int upper = (pwd_len - lower) /2;
int num = (pwd_len - lower) / 2;
int symbol = pwd_len - lower - upper - num ;
StringBuffer pwd = new StringBuffer();
Random random = new Random();
int position = 0;
while((lower + upper + num + symbol) > 0 ){
if(lower > 0){
position = random.nextInt(pwd.length() + 1);
pwd.insert(position,LOWER_CASES[random.nextInt(LOWER_CASES.length)]);
lower--;
}
if(upper > 0){
position = random.nextInt(pwd.length() + 1);
pwd.insert(position,UPPER_CASES[random.nextInt(UPPER_CASES.length)]);
upper--;
}
if(num > 0){
position = random.nextInt(pwd.length() + 1);
pwd.insert(position,NUMS_LIST[random.nextInt(NUMS_LIST.length)]);
num--;
}
if(symbol > 0){
position = random.nextInt(pwd.length() + 1);
pwd.insert(position,SYMBOLS_ARRAY[random.nextInt(SYMBOLS_ARRAY.length)]);
symbol--;
}
System.out.println(pwd.toString());
}
return pwd.toString();
}
今天的文章Java 生成随机密码分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/32096.html