The only advice I'd offer here is to replace '62' with a calculated string length of the pass characters, and also place that variable outside of the loop. Never worth the hassle of using magic numbers.
Good idea there about removing those similar characters, that's not something I've considered before.
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 ;
}