All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.mycomm.itool.security.StrongPassword Maven / Gradle / Ivy

The newest version!
package com.mycomm.itool.security;

import java.util.Random;

public class StrongPassword {
    private static final char [] A_Z = {'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'};
    private static final char [] a_z = {'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'};
    private static final char [] num = {'0','1','2','3','4','5','6','7','8','9'};
    private static final char [] specials = {'`','~','!','@','#','$','%','^','&','*','(',')','_','-','=','+','[','{',']','}','|',';',':','"','\'',',','<','.','>','/','?'};
    private static final char [] specials_full = {'`','~','!','@','#','$','%','^','&','*','(',')','_','-','=','+','[','{',']','}','\\','|',';',':','"','\'',',','<','.','>','/','?'};

    public static String generatePassword(int passwordLength) throws Exception {
        if(passwordLength < 8){
            throw new Exception("Password Length must greater than or equal 8!");
        }
        StringBuilder strongPassword = new StringBuilder();
        strongPassword.append(randomAZ());
        strongPassword.append(random_az());
        strongPassword.append(randomNum());
        strongPassword.append(random_special());
        buildRandomString(passwordLength -4,strongPassword);
        return strongPassword.toString();
    }
    private static void buildRandomString(int times,StringBuilder data){
        Random random = new Random();
        while (data.length() < times){

            int range = random.nextInt(4);
            char tmp = '.';
            if(range == 0){
                tmp = (A_Z[random.nextInt(A_Z.length)]);
            }if(range == 1){
                tmp = (a_z[random.nextInt(a_z.length)]);
            }if(range == 2){
                tmp = (num[random.nextInt(num.length)]);
            }if(range == 3){
                tmp = (specials[random.nextInt(specials.length)]);
            }
            if(data.indexOf(tmp+"") > 0){
                continue;
            }
            data.append(tmp);

        }
    }

    private static char randomAZ(){
        return A_Z[new Random().nextInt(A_Z.length)];
    }

    private static char random_az(){
        return a_z[new Random().nextInt(a_z.length)];
    }

    private static char randomNum(){
        return num[new Random().nextInt(num.length)];
    }

    private static char random_special(){
        return specials[new Random().nextInt(specials.length)];
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy