随机生成指定长度的密码之---Random
Posted 幽雨_rain
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了随机生成指定长度的密码之---Random相关的知识,希望对你有一定的参考价值。
随机生成指定长度的密码思路:
1.密码中可能包含字母,数字,特殊符号,为了区别分别定义常量
2.随机生成密码,自然想到要用到java.util.Random 类
3.定义一个带两个参数的方法,1跟2,分别指定密码内容类型和密码长度
具体实现过程:
import java.util.Random;
/**
* @author
* @date 创建时间:
* @version 1.0
* @parameter
* @since
* @return
*/
public class RandomChar {
private static final String CHAR_ALL = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
private static final String CHAR_LOWERCASE = "qwertyuiopasdfghjklzxcvbnm";
private static final String CHAR_UPPERCASE = "QWERTYUIOPLAKSJDHFGZXCVBNM";
private static final String NUMBERS = "0123456789";
private static final String ALL = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
private static final String CHAR_SPECIAL_ALL = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM~!@#$%^&*";
public static final int RANDOM_CHAR_UPPERCASE = 0;
public static final int RANDOM_CHAR_LOWERCASE = 1;
public static final int RANDOM_CHAR_ALL = 2;
public static final int RANDOM_NUMBERS = 3;
public static final int RANDOM_ALL = 4;
public static final int RANDOM_SPECIAL_ALL = 5;
/**
* @author
* @date 创建时间:2016-11-28 下午10:38:52
* @version 1.0
* @parameter1 type
* @parameter2 len
* @since
* @return String
*/
public static String getChars(int type, int len) {
Random random = new Random();
int i = 0;
String random_source = null;
switch (type) {
case RANDOM_CHAR_UPPERCASE:
random_source = CHAR_UPPERCASE;
break;
case RANDOM_CHAR_LOWERCASE:
random_source = CHAR_LOWERCASE;
break;
case RANDOM_CHAR_ALL:
random_source = CHAR_ALL;
break;
case RANDOM_NUMBERS:
random_source = NUMBERS;
break;
case RANDOM_ALL:
random_source = ALL;
break;
case RANDOM_SPECIAL_ALL:
random_source = CHAR_SPECIAL_ALL;
break;
default:
random_source = CHAR_SPECIAL_ALL;
break;
}
int length = random_source.length();
String result = "";
while (i < len) {
int v = Math.abs(random.nextInt()) % length;
result += random_source.substring(v, v + 1);
i++;
}
return result;
}
public static void main(String[] args)
{
String newPasswd=RandomChar.getChars(4, 6);
System.out.println("新密码是:"+newPasswd);
}
}
有兴趣的可以参考java源码中Random类具体实现方法。
参考链接:http://www.cnblogs.com/chenning/p/4873422.html
以上是关于随机生成指定长度的密码之---Random的主要内容,如果未能解决你的问题,请参考以下文章