生成随机密码的工具类

场景:比如说我们这边有个后台系统,用户注册(不让填写密码,密码由后台生成),如果注册成功,通过邮件的形式发送给用户。这样的场景大家应该都见过吧。这里的密码就是我们通过这个工具类就可以生成

PasswordUtil.java

package com.mmall.util;

import com.mmall.model.SysUser;

import java.util.Date;
import java.util.Random;

public class PasswordUtil {

    public final static String[] word = {
            "a", "b", "c", "d", "e", "f", "g",
            "h", "j", "k", "m", "n",
            "p", "q", "r", "s", "t",
            "u", "v", "w", "x", "y", "z",
            "A", "B", "C", "D", "E", "F", "G",
            "H", "J", "K", "M", "N",
            "P", "Q", "R", "S", "T",
            "U", "V", "W", "X", "Y", "Z"
    };

    public final static String[] num = {
            "2", "3", "4", "5", "6", "7", "8", "9"
    };

    public static String randomPassword() {
        StringBuffer stringBuffer = new StringBuffer();
        Random random = new Random(new Date().getTime());
        boolean flag = false;
        //输出几位密码长度  这里是有可能8 ,9 ,10 位
        int length = random.nextInt(3) + 8;
        for (int i = 0; i < length; i++) {
            if (flag) {
                stringBuffer.append(num[random.nextInt(num.length)]);
            } else {
                stringBuffer.append(word[random.nextInt(word.length)]);
            }
            flag = !flag;
        }
        return stringBuffer.toString();
    }

    public static void main(String[] args) throws Exception {
        System.out.println(randomPassword());
        Thread.sleep(100);
        System.out.println(randomPassword());
        Thread.sleep(100);
        System.out.println(randomPassword());
    }
}
View Code

密码长度可以变,代码很简单。就不详细介绍了。

原文地址:https://www.cnblogs.com/coder-lzh/p/8661284.html