生成随机密码的工具类

public class PasswordUtil {
    /**
     * 根据条件获得复杂密码
     * @param num  密码的位数 6-32位
     * @param inNum 是否包含数字,默认为1
     * @param inStr 是否包含大写字母,默认为1
     * @param inSpec 是否包含特殊字符,默认为0
     * 默认包含小写字母,没有条件时,将全部使用小写字母
     * @return 生成的密码
     */
    public String getPassword(int num,int inNum,int inStr,int inSpec) {
        String [] strs = new String[num];
        // 密码的第一位为字母
        if (inStr==1) {
            strs[0] = this.getRandomStr();
        }else {
            strs[0] = this.getRandomStr().toLowerCase();
        }
        // 生成从第二位开始的密码
        for (int i=1;i<num;i++) {
            String funcIndex = this.getFormIndex();
            // funcIndex=num时候,调用生成数字的方法;=str时,生成大写字母;=spec时,生成特殊字符。
            if (funcIndex.equals("num") && inNum==1) {
                strs[i] = String.valueOf(this.getRandomNum());
            } else if (funcIndex.equals("str") && inStr==1) {
                strs[i] = this.getRandomStr();
            } else if (funcIndex.equals("spec") && inSpec==1) {
                strs[i] = this.getSpecStr();
            } else {
                // 当不满足生成的条件时,生成小写字母
                strs[i] = this.getRandomStr().toLowerCase();
            }
        }
        String str = "";
        for (String s :strs) {
            str += s;
        }
        return str;
    }

    private int getRandomNum() {
        int num = (int) (Math.random()*10);
        return num;
    }
    private String getRandomStr() {
        String [] strs= {
                "Q","W","E","R","T",
                "Y","U","I","O","P",
                "A","S","D","F","G","H","J","K",
                "L","Z","X","C","V","B","N","M"};
        int strIndex = (int) (Math.random()*26);
        int strUpper =  ( (int)(Math.random()*100) )%2;
        if (strUpper!=1) {
            return strs[strIndex].toLowerCase();
        }
        return strs[strIndex];
    }
    private String getSpecStr() {
        String [] strs= {"!","@","_","#","$"};
        int strIndex = (int) (Math.random()*5);
        return strs[strIndex];
    }

    private String getFormIndex() {
        int formIndex =(int)(Math.random()*16);
        if ((formIndex%3)==0) {
            return "num";
        }else if ((formIndex%5)==1) {
            return "spec";
        }else {
            return "str";
        }
    }

}



posted @ 2020-01-14 14:52  HanJunOvO  阅读(523)  评论(0编辑  收藏  举报