随机密码

public class RandomPwd {

    private static final String SPECIAL_CHARS = "! @#$%^&*_=+-/";

    /**
    *在给用户生成账号时,经常需要给用户生成一个默认随机密码,然后通过邮件或短信发给用户,
     * 作为初次登录使用。我们假定密码是6位数字
    **/
    private static String randomPassword6() {
        char[] chars = new char[6];
        Random rnd = new Random();
        for (int i = 0; i < 6; i++) {
            chars[i] = (char)('0' + rnd.nextInt(10));
        }
        return new String(chars);
    }

    /**
    *要求是8位密码,字符可能由大写字母、小写字母、数字和特殊符号组成
    **/
    public static String randomPassword8() {
        char[] chars = new char[8];
        Random rnd = new Random();
        for (int i = 0; i < 8; i++) {
            chars[i] = nextChar(rnd);
        }
        return new String(chars);
    }

    /**
    * 要求是8位密码 至少要含一个大写字母、一个小写字母、一个特殊符号、一个数字
    **/
    public static String randomPassword81() {
        char[] chars = new char[8];
        Random rnd = new Random();
        chars[nextIndex(chars, rnd)] = nextSpecialChar(rnd);
        chars[nextIndex(chars, rnd)] = nextUpperLetter(rnd);
        chars[nextIndex(chars, rnd)] = nextLowerLetter(rnd);
        chars[nextIndex(chars, rnd)] = nextNumLetter(rnd);
        for (int i = 0; i < 8; i++) {
            if (chars[i] == 0) {
                chars[i] = nextChar(rnd);
            }
        }
        return new String(chars);
    }

    private static int  nextIndex(char[] chars, Random rnd) {
        int index = rnd.nextInt(chars.length);
        while (chars[index] != 0) {
            index = rnd.nextInt(chars.length);
        }
        return index;
    }

    private static char nextChar(Random rnd) {
        switch (rnd.nextInt(4)) {
            case 0:
                return nextLowerLetter(rnd);
            case 1:
                return nextUpperLetter(rnd);
            case 2:
                return nextNumLetter(rnd);
            default :
                return nextSpecialChar(rnd);
        }
    }

    private static char nextSpecialChar (Random rnd) {
        return SPECIAL_CHARS.charAt(rnd.nextInt(SPECIAL_CHARS.length()));
    }

    private static char nextUpperLetter(Random rnd) {
        return (char)('A' + rnd.nextInt(26));
    }

    private static char nextLowerLetter(Random rnd) {
        return (char)('a' + rnd.nextInt(26));
    }

    private static char nextNumLetter(Random rnd) {
        return (char)('0' + rnd.nextInt(10));
    }
}
发布了89 篇原创文章 · 获赞 38 · 访问量 4万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 精致技术 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览