Search code examples
javarandompasswordstemporary

JAVA Can someone explain this code for me? Auto-Gen


I found these codes online at:

http://www.java2s.com/Code/Java/Security/GeneratearandomStringsuitableforuseasatemporarypassword.htm

But I am not really sure about the codes' logic.

public static String generateRandomPassword()
{

      String letters = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789";

      String pw = "";
      for (int i=0; i<PASSWORD_LENGTH; i++)
      {
          int index = (int)(RANDOM.nextDouble()*letters.length());
          pw += letters.substring(index, index+1); 
      }
      return pw;
}

Can someone explain this two lines of codes for me so I can understand better?

int index = (int)(RANDOM.nextDouble()*letters.length());
pw += letters.substring(index, index+1); 

Thank You. :D


Solution

  • int index = (int)(RANDOM.nextDouble()*letters.length()); Generates a random double greater than or equal to 0.0 and less than 1.0. Then it multiples the result by the length of your string of acceptable letters. Essentially, in these two steps, you have number between 0 (inclusive) and the total number of valid "letters", but it is a double, so it has a decimal part. That number is casted to an int (a whole number) and saved into the index variable.

    pw += letters.substring(index, index+1); Concatenates pw with a substring of the letters string. The substring begins at the index determined by the line above and ends at index + 1 (not including the character at index + 1). Essentially, this part makes a substring of one character at the index determined by the random integer generated above. It then concatenates it onto the existing pw string.

    Example of steps:

    int index = (int)(RANDOM.nextDouble()*letters.length());:

    1. RANDOM.nextDouble() => 0.51
    2. letters.length() => 60
    3. RANDOM.nextDouble()*letters.length() => 30.6
    4. (int)(RANDOM.nextDouble()*letters.length()) => 30

    pw += letters.substring(index, index+1);:

    1. letters.substring(index, index+1) => "H"
    2. pw += letters.substring(index, index+1) => "" + "H" => "H"