码迷,mamicode.com
首页 > 其他好文 > 详细

随机生成指定长度的密码之---Random

时间:2016-11-29 06:58:38      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:1.0   private   ges   etc   技术分享   abs   special   i++   字母   

随机生成指定长度的密码思路:

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

标签:1.0   private   ges   etc   技术分享   abs   special   i++   字母   

原文地址:http://www.cnblogs.com/Ant-soldier/p/6111811.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!