java中生成随机密码

来源:互联网 发布:移动网络机顶盒遥控器 编辑:程序博客网 时间:2024/06/10 13:30

java中生成随机密码的方法:

str+=(char)(Math.Random()*26 + ‘A’); //随机生成大写字母

//密码的类型,枚举类型 public enum PasswordType {    UpCase,         //大写    LowerCase,      //小写    Number,         //数字    Mixed           //混合}

以下是主要的方法

 public class RandomPSWd {    /**     *  随机生成1-10位的密码     * @param pwdType   密码类型,大写,小写,数字 或三都的混合     * @param length    生成密码的长度     * @return  密码字符串     */      public String GernaratePWD(PasswordType pwdType,int length) {        String rtnstr="";               try {            for(int i =0;i<length;i++){                switch (pwdType) {                case UpCase:                    rtnstr += (char)(Math.random() * 26 + 'A');    //生成随机大写字母                    break;                case LowerCase:                    rtnstr += (char)(Math.random() * 26 + 'a');  //生成随机小写字母                    break;                case Number:                    rtnstr += String.valueOf((int)(Math.random() * 10));  //生成随机数字                     break;                case Mixed:        //生成随机大写字母、小写字母或数字                    Random random = new Random();                    switch (random.nextInt(3)) {                    case 0:                        rtnstr += (char)(Math.random() * 26 + 'A');                        break;                    case 1:                        rtnstr += (char)(Math.random() * 26 + 'a');                        break;                    case 2:                        rtnstr += String.valueOf((int)(Math.random() * 10));                        break;                    default:                        break;                    }                    break;                default:                    break;                }            }        } catch (Exception e) {            rtnstr = "";        }        return rtnstr;    }

测试用例

 public class Test {    /**     * 随机生成密码字符串的用法      * @param args     */    public static void main(String[] args) {        int length = (int)( Math.random()*10 + 1);      // 1-10位        System.out.println("随机" + length +"位大写字母:" +(new RandomPSWd()).GernaratePWD(PasswordType.UpCase, length));        System.out.println("随机" + length +"位小写字母:" +(new RandomPSWd()).GernaratePWD(PasswordType.LowerCase, length));        System.out.println("随机" + length +"位数字:" +(new RandomPSWd()).GernaratePWD(PasswordType.Number, length));        System.out.println("随机" + length +"位混合密码:" +(new RandomPSWd()).GernaratePWD(PasswordType.Mixed, length));    }}