random password generator in java code example

Example 1: generate random password in java

import java.util.Random;

public class PasswordGenerator {
	public static String generateRandomPassword(int len) {
		String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghi"
          +"jklmnopqrstuvwxyz!@#$%&";
		Random rnd = new Random();
		StringBuilder sb = new StringBuilder(len);
		for (int i = 0; i < len; i++)
			sb.append(chars.charAt(rnd.nextInt(chars.length())));
		return sb.toString();
	}
}

Example 2: generta epassword java

public static String generateRandomPassword(int length) {
        Object[][] characterSets = {
                {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'},
                {'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'},
                {'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'}
        };
        List<Character> passwordCharacters = new ArrayList<>();
        ThreadLocalRandom random = ThreadLocalRandom.current();
        for (Object[] characters : characterSets){
            for (int i = 0; i < length / 3; i++){
                passwordCharacters.add((Character) characters[random.nextInt(0, characters.length)]);
            }
        }
        for (int i =0; i < length % 3; i++){
            Object[] characters = characterSets[random.nextInt(0, characterSets.length)];
            passwordCharacters.add((Character) characters[random.nextInt(0, characters.length)]);
        }
        Collections.shuffle(passwordCharacters);
        StringBuilder stringBuilder = new StringBuilder(length);
        passwordCharacters.forEach(stringBuilder::append);
        return stringBuilder.toString();
    }

Tags:

Java Example