随机生成密码工具类

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Random;

public class SecurityUtil {

    /**
     * 普通md5加密,返回小写
     *
     * @param data 加密数据
     * @return
     */
    public static String MD5(String data) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] array = md.digest(data.getBytes(StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            for (byte item : array) {
                sb.append(Integer.toHexString((item & 0xFF) | 0x100), 1, 3);
            }
            return sb.toString();
        } catch (Exception e) {

        }
        return null;
    }

    /**
     * md5加密
     *
     * @param data  加密数据
     * @param index 加密次数
     * @return
     */
    public static String MD5(String data, int index) {
        for (int i = 0; i < index; i++) {
            data = MD5(data);
        }
        return data;
    }

    /**
     * 随机生成指定位数的密码
     *
     * @param len 密码长度
     * @return
     */
    public static String randomStr(int len) {
        String str;
        char[] charArr = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".toCharArray();
        StringBuilder sb = new StringBuilder();
        Random r = new Random();

        for (int x = 0; x < len; ++x) {
            sb.append(charArr[r.nextInt(charArr.length)]);
        }
        str = sb.toString();

        String pattern1 = ".*[a-z]+.*";
        String pattern2 = ".*[A-Z]+.*";
        String pattern3 = ".*[0-9]+.*";

        if (!(str.matches(pattern1) && str.matches(pattern2) &&
                str.matches(pattern3))) {
            str = randomStr(len);
        }

        return str;
    }

    /**
     * 随机生成指定位数的密码
     *
     * @param len 密码长度
     * @return
     */
    public static String randomNum(int len) {
        String str;
        char[] charArr = "1234567890".toCharArray();
        StringBuilder sb = new StringBuilder();
        Random r = new Random();

        for (int x = 0; x < len; ++x) {
            sb.append(charArr[r.nextInt(charArr.length)]);
        }
        return sb.toString();
    }
}

 

posted @ 2023-07-22 15:28  fnasklf  阅读(63)  评论(0编辑  收藏  举报