Java password generator example
By:Roy.LiuLast updated:2019-08-11
A Java example to generate a strong, secure random password containing [a-zA-Z0-9!@#$%&*()_+-=[]?] characters, with a length of 15.
PasswordGenerator.java
package com.mkyong; import java.security.SecureRandom; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; public class PasswordGenerator { private static final String CHAR_LOWER = "abcdefghijklmnopqrstuvwxyz"; private static final String CHAR_UPPER = CHAR_LOWER.toUpperCase(); private static final String NUMBER = "0123456789"; private static final String OTHER_CHAR = "!@#$%&*()_+-=[]?"; private static final String PASSWORD_ALLOW_BASE = CHAR_LOWER + CHAR_UPPER + NUMBER + OTHER_CHAR; // optional, make it more random private static final String PASSWORD_ALLOW_BASE_SHUFFLE = shuffleString(PASSWORD_ALLOW_BASE); private static final String PASSWORD_ALLOW = PASSWORD_ALLOW_BASE_SHUFFLE; private static SecureRandom random = new SecureRandom(); public static void main(String[] args) { System.out.format("String for password \t\t\t: %s%n", PASSWORD_ALLOW_BASE); System.out.format("String for password (shuffle) \t: %s%n%n", PASSWORD_ALLOW); // generate 5 random password for (int i = 0; i < 5; i++) { System.out.println("password : " + generateRandomPassword(15)); System.out.println("\n"); public static String generateRandomPassword(int length) { if (length < 1) throw new IllegalArgumentException(); StringBuilder sb = new StringBuilder(length); for (int i = 0; i < length; i++) { int rndCharAt = random.nextInt(PASSWORD_ALLOW.length()); char rndChar = PASSWORD_ALLOW.charAt(rndCharAt); // debug System.out.format("%d\t:\t%c%n", rndCharAt, rndChar); sb.append(rndChar); return sb.toString(); // shuffle public static String shuffleString(String string) { List<String> letters = Arrays.asList(string.split("")); Collections.shuffle(letters); return letters.stream().collect(Collectors.joining());
Output
String for password : abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%&*()_+-=[]? String for password (shuffle) : o]XrVD)-cluv0FPq*mO+[GW8zSbB1EHA7%iyYjTeNs=Qx2@w95kf_ZJCn?3U#p6RI!a$LtKgdMh(4& 70 : K 23 : 8 77 : & 50 : k 17 : m 59 : U 14 : P 57 : ? 65 : ! 67 : $ 22 : W 8 : c 18 : O 1 : ] 11 : v password : K8&kmUP?!$WcO]v 50 : k 57 : ? 53 : Z 58 : 3 42 : = 61 : p 64 : I 4 : V 39 : e 12 : 0 23 : 8 2 : X 55 : C 18 : O 42 : = password : k?Z3=pIVe08XCO= 61 : p 35 : y 53 : Z 50 : k 26 : b 74 : h 4 : V 30 : H 70 : K 37 : j 54 : J 25 : S 39 : e 49 : 5 36 : Y password : pyZkbhVHKjJSe5Y 16 : * 70 : K 77 : & 66 : a 27 : B 6 : ) 64 : I 55 : C 72 : d 51 : f 28 : 1 14 : P 0 : o 60 : # 58 : 3 password : *K&aB)ICdf1Po#3 3 : r 43 : Q 40 : N 6 : ) 71 : g 18 : O 49 : 5 35 : y 52 : _ 30 : H 64 : I 59 : U 24 : z 72 : d 72 : d password : rQN)gO5y_HIUzdd
From:一号门
COMMENTS