Java生成16位随机密码(包含大小写字母、数字、特殊符号)

2022-11-01

static char[] str1 = {
                   'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
                   'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
                   'u', 'v', 'w', 'x', 'y', 'z'
};
static char[] str2 = {
       'A', 'B', 'C', 'D','E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
       'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y' ,'Z'
};
static char[] str3 = {'0', '1', '2', '3', '4', '5', '6', '7','8', '9'};
static char[] str4 = {'!', '@', '#', '$', '%', '^', '&', '*'};
//创建随机密码
public static String createPassWord(int len){

   StringBuffer sb = new StringBuffer();
   int rdGet;//取得随机数

   int count=0;
   int f = 0;
   boolean b1 = false, b2 = false, b3 = false;
   int b4 = 0;
   while(count < len){
       Random rd = new Random();
       f = (int)(Math.random()*4);
       if(count > 4){
           if(!b1){
               f = 0;
               b1 = true;
           }else if(!b2){
               f = 1;
               b2 = true;
           }else if(!b3){
               f = 2;
               b3 = true;
           }else if(b4 == 0){
               f = 3;
           }
       }

       if(f == 0){
           rdGet = Math.abs(rd.nextInt(26));//生成的数最大为62-1
           sb.append(str1[rdGet]);
           count ++;
       }else if(f == 1){
           rdGet = Math.abs(rd.nextInt(26));//生成的数最大为62-1
           sb.append(str2[rdGet]);
           count ++;
       }else if(f == 2){
           rdGet = Math.abs(rd.nextInt(10));//生成的数最大为62-1
           sb.append(str3[rdGet]);
           count ++;
       }else if(f == 3){
           if(b4 > 1){
               continue;
           }
           rdGet = Math.abs(rd.nextInt(8));//生成的数最大为62-1
           sb.append(str4[rdGet]);
           count ++;
           b4++;
       }

   }
   return sb.toString();
}