2008年10月9日 星期四

[備忘記]Java 如何製作亂數產生的密碼

public String makePassword(int passwordLength){
 //密碼的字符表(可以亂排,至於要不要有特殊字元就看後續的處理可否允許特殊字元的輸入)
 char[] word =
  {'a','b','c','d','e','f',
  'g','h','i','j','k','L',
  'm','0','n','o','1','2',
  '3','p','4','q','5','r',
  's','6','t','7','u','v',
  '8','w','x','9','y','z'};
 byte[] randomNumber = new byte[passwordLength];
 new Random().nextBytes(randomNumber);
 StringBuilder password = new StringBuilder();
 for(int i = 0; i < randomNumber.length; i++){
  password.append(word[Math.abs(randomNumber[i]) % word.length]);
 }
 return password.toString();
}

沒有留言: