当前位置: 代码迷 >> 综合 >> 传入密码长度,随机生成密码及检测密码:必须由大写字母、小写字母、数字和特殊符号共同组成
  详细解决方案

传入密码长度,随机生成密码及检测密码:必须由大写字母、小写字母、数字和特殊符号共同组成

热度:41   发布时间:2024-01-30 12:47:33.0
package com.test;import java.util.Random;
import java.util.Scanner;public class Main {/*** 主方法** @param args*/public static void main(String[] args) {Scanner in = new Scanner(System.in);//传入密码长度int len = in.nextInt();//调用密码生成方法System.out.println(makeRandomPassword(len));}/*** 密码随机生成:包含大小写字母、数字、字符** @param len* @return*/public static String makeRandomPassword(int len) {//最小保证大小写字母、数字、字符各有一个if (len < 4) {return "密码长度最小为4!";}//拼接密码StringBuilder sbu = new StringBuilder();//生成随机对象Random rd = new Random();//大写字母字符串String capital = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";//小写字母字符串String letter = "abcdefghijklmnopqrstuvwxyz";//数字字符串String number = "1234567890";//符号字符串String symbol = "~!@#$%^&*()_-+={}[]/?,.\"<>\\|:;\'`";//字符串转数组char charr[] = (capital + letter + number + symbol).toCharArray();//随机抽取for (int i = 0; i < len; i++) {sbu.append(charr[rd.nextInt(charr.length)]);}//存储密码String randomPassword = sbu.toString();//是否有大写字母Boolean b1 = randomPassword.matches(".*[A-Z]{1,}.*");//是否含有小写字母Boolean b2 = randomPassword.matches(".*[a-z]{1,}.*");//是否含有数字Boolean b3 = randomPassword.matches(".*\\d{1,}.*");//是否含有字符Boolean b4 = randomPassword.matches(".*[<>(){}|~!@#$%^&*\\\\.\\'\\\"`_?-]{1,}.*");//条件判断if (b1 & b2 & b3 & b4) {return randomPassword;} else {//不满足则重新调用方法randomPassword = makeRandomPassword(len);System.out.println("=======");}return randomPassword;}
}
  相关解决方案