java auto generate password

java automatically generates a password, and must contain three of the four types of uppercase and lowercase letters, numbers, and special characters

package com.yili;

import java.util.Random;

/**
 * Created by Han Xide on 2017/7/23.
 */
public class Test {
    public static void main(String[] args) {

        String password = getRandomPassword(8);
        System.out.println(password);
    }

    //Get the verified random password
    public static String getRandomPassword(int len) {
        String result = null;

        /*if(len >= 6) {
            for (result = makeRandomPassword (len); len> = 6; result = makeRandomPassword (len)) {
                if (result.matches(".*[a-z]{1,}.*") && result.matches(".*[A-Z]{1,}.*") && result.matches(".*\\d{1,}.*") && result.matches(".*[~!@#$%^&*\\.?]{1,}.*")) {
                    return result;
                }
            }
        }*/
        while(len>=6){
            result = makeRandomPassword (len);
            if (result.matches(".*[a-z]{1,}.*") && result.matches(".*[A-Z]{1,}.*") && result.matches(".*\\d{1,}.*") && result.matches(".*[~!@#$%^&*\\.?]{1,}.*")) {
                return result;
            }
            result = makeRandomPassword (len);
        }
        return "Length must not be less than 6 digits!";
    }
    //Generate random password
    public static String makeRandomPassword(int len){
        char charr[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890~!@#$%^&*.?".toCharArray();
        //System.out.println("Charr array length:" + charr.length); //You can see how many times this method is called
        StringBuilder sb = new StringBuilder();
        Random r = new Random();

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

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327070663&siteId=291194637