用Java生成密码
现在,如今几乎每个网站都要求生成临时密码。如果用户忘记了密码,系统会根据公司的密码策略生成随机密码。以下示例生成遵循以下条件的随机密码-
它应至少包含一个大写字母。
它应至少包含一个小写字母。
它应至少包含一个数字。
长度应为8个字符。
它应包含以下特殊字符之一:@,$,#,!。
示例
import java.util.Random; public class Tester{ public static void main(String[] args) { System.out.println(generatePassword(8)); } private static char[] generatePassword(int length) { String capitalCaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; String lowerCaseLetters = "abcdefghijklmnopqrstuvwxyz"; String specialCharacters = "!@#$"; String numbers = "1234567890"; String combinedChars = capitalCaseLetters + lowerCaseLetters + specialCharacters + numbers; Random random = new Random(); char[] password = new char[length]; password[0] = lowerCaseLetters.charAt(random.nextInt(lowerCaseLetters.length())); password[1] = capitalCaseLetters.charAt(random.nextInt(capitalCaseLetters.length())); password[2] = specialCharacters.charAt(random.nextInt(specialCharacters.length())); password[3] = numbers.charAt(random.nextInt(numbers.length())); for(int i = 4; i< length ; i++) { password[i] = combinedChars.charAt(random.nextInt(combinedChars.length())); } return password; } }
输出结果
cF#0KYbY