Skip to content

Commit dee9622

Browse files
committed
password generator snippet
1 parent f5b07b5 commit dee9622

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
---
2+
title: Password Generator
3+
description: Generates a random string with specified length and character set, including options for letters, numbers, and special characters
4+
author: Mcbencrafter
5+
tags: string,password,generator,security,random,token
6+
---
7+
8+
```java
9+
public static String randomString(int length, boolean useLetters, boolean useNumbers, boolean useSpecialCharacters) {
10+
String characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
11+
String numbers = "0123456789";
12+
String specialCharacters = "!@#$%^&*()_+-=[]{}|;:,.<>?";
13+
14+
String allowedCharacters = "";
15+
16+
if (useLetters)
17+
allowedCharacters += characters;
18+
19+
if (useNumbers)
20+
allowedCharacters += numbers;
21+
22+
if (useSpecialCharacters)
23+
allowedCharacters += specialCharacters;
24+
25+
SecureRandom random = new SecureRandom();
26+
StringBuilder result = new StringBuilder(length);
27+
28+
for (int i = 0; i < length; i++) {
29+
int index = random.nextInt(allowedCharacters.length());
30+
result.append(allowedCharacters.charAt(index));
31+
}
32+
33+
return result.toString();
34+
}
35+
36+
// Usage:
37+
System.out.println(randomString(10, true, true, false)); // Random string containing letters, numbers but no special characters with 10 characters
38+
```

0 commit comments

Comments
 (0)