|
1 | 1 | package password_generator; |
2 | | - |
3 | | -import java.util.Scanner; |
4 | | -import java.security.SecureRandom; |
| 2 | +import java.util.Scanner; |
| 3 | +import java.security.SecureRandom; // Import the SecrureRandom package |
| 4 | +// Here we are using 'SecureRandom' instead of 'Random' for more secure password |
5 | 5 |
|
6 | 6 | public class password_generator_2 { |
7 | 7 |
|
8 | | - public String generatePassword(int length) { |
| 8 | +// Create an method with a length parameter |
| 9 | + public String generatePassword(int length) { |
9 | 10 | String pwd_characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%&"; |
10 | 11 | SecureRandom random = new SecureRandom(); |
| 12 | + |
| 13 | +// StringBuilder to efficiently build the password character by character |
11 | 14 | StringBuilder password = new StringBuilder(); |
12 | 15 |
|
13 | 16 | for (int i = 0; i < length; i++) { |
| 17 | + |
| 18 | +// Generate an random index from the length of the pwd_characters |
14 | 19 | char randomChar = pwd_characters.charAt(random.nextInt(pwd_characters.length())); |
| 20 | + |
| 21 | +// append the generated random characters into 'password' |
15 | 22 | password.append(randomChar); |
16 | 23 | } |
17 | 24 |
|
| 25 | +// Returning password as an proper String |
18 | 26 | return password.toString(); |
19 | 27 | } |
20 | 28 | public static void main(String[] args) { |
| 29 | + |
| 30 | +// Create an object for an public class |
21 | 31 | password_generator_2 generator = new password_generator_2(); |
22 | 32 | Scanner sc = new Scanner(System.in); |
23 | 33 | System.out.println(); |
24 | | - System.out.println("Enter the length of the password: "); |
| 34 | + System.out.println("Enter the length of the password: "); // Take the |
25 | 35 | int passwordLength = sc.nextInt(); |
| 36 | + |
| 37 | +// Calling an method using object with an Variable |
26 | 38 | String password = generator.generatePassword(passwordLength); |
27 | 39 | System.out.println("______________________________________________"); |
28 | 40 | System.out.println(); |
29 | | - System.out.println("The Password: " + password); |
| 41 | + System.out.println("The Password: " + password); // Lets print the generated password |
30 | 42 | System.out.println("______________________________________________"); |
31 | 43 | } |
32 | 44 |
|
|
0 commit comments