Random password generation





8
Date Submitted Sat. Oct. 28th, 2006 3:00 PM
Revision 1 of 1
Scripter SCoon
Tags Java | Password
Comments 0 comments
import java.util.Random;

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);
  }



}
 

Vladislav Zlobin

Comments

There are currently no comments for this snippet.

Voting