Random Password Generation
7
Change logs
-> length calculated from the array
-> charachters will not be repeated in the password
-> length calculated from the array
-> charachters will not be repeated in the password
/* This method is used to generate a random password
* @ params int - length of the password
* @ return String - random password
*/
public String generateRandomPassword(int length){
String passarray = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
long range = passarray.length();
String passwd = "";
for(int i = 0; i < length; ){
Random generator = new Random();
int rnd = (int)(range * generator.nextDouble());
String ch = passarray.substring(rnd,rnd+1);
if(passwd.indexOf(ch)==-1){
passwd = passwd + ch;
i++;
}
}
return passwd;
}






generateRandomPassword(int length,boolean alpha,boolean numeric,boolean punc);
And depending on the boolean parameters, you could specify a password with just numbers/letters/punc, or a combination.
If you wanted to do it in one parameter you could always use Xor flags, but I never liked those.
Anyways, thanks for the snippet.
Also this code fragment makes your code unstable: just call generateRandomPassword(100).
class PasswordGenerator {
public static void main(String[] args) throws Exception {
PasswordGenerator passwordGenerator = new PasswordGenerator();
for (int i = 20; i <= 100; i++) {
System.out.println(passwordGenerator.generate(PRINTABLE_CHARACTERS, i));
}
}
protected Random m_generator = new Random();
public static final String DIGITS = "0123456789";
public static final String LOCASE_CHARACTERS = "abcdefghijklmnopqrstuvwxyz";
public static final String UPCASE_CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static final String PRINTABLE_CHARACTERS = DIGITS + LOCASE_CHARACTERS + UPCASE_CHARACTERS;
public String generate (String chars, int passLength) throws Exception {
if (passLength > chars.length()) {
throw new Exception("Password generation is imposible");
}
char[] availableChars = chars.toCharArray();
int availableCharsLeft = availableChars.length;
StringBuffer temp = new StringBuffer(passLength);
for (int i = 0; i < passLength; i++) {
int pos = (int) (availableCharsLeft * m_generator.nextDouble());
temp.append(availableChars[pos]);
availableChars[pos] = availableChars[availableCharsLeft - 1];
--availableCharsLeft;
}
return String.valueOf(temp);
}
}
Good idea there about removing those similar characters, that's not something I've considered before.
The only difference is that I left out letters that can be easily mistaken for each other...
B I O S Z i l o s v z 0
Tim
private String genPassword( int length )
{
final String letters = "ACDEFGHJKLMNPQRTUVWXYabcdefghjkmnpqrtuwxy123456789" ;
String ret = "" ;
while( ret.length() < length )
{
ret += letters.charAt( (int)( Math.random() * letters.length() ) ) ;
}
return ret ;
}