Skip to content

Commit 7c5e5fb

Browse files
committed
Fixed password generator
1 parent a84d0ce commit 7c5e5fb

File tree

1 file changed

+34
-24
lines changed

1 file changed

+34
-24
lines changed

src/app/keygen/page.jsx

+34-24
Original file line numberDiff line numberDiff line change
@@ -127,31 +127,41 @@ export default function KeygenPage() {
127127
};
128128

129129
const generatePassword = () => {
130-
setIsPasswordLoading(true);
131-
const length = 16;
132-
const uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
133-
const lowercase = 'abcdefghijklmnopqrstuvwxyz';
134-
const numbers = '0123456789';
135-
const symbols = '!@#$%^&*()_+-=[]{}|;:,.<>?';
136-
const alphabet = uppercase + lowercase + numbers + symbols;
137-
138-
let password = '';
139-
// Ensure at least one of each type
140-
password += uppercase[Math.floor(Math.random() * uppercase.length)];
141-
password += lowercase[Math.floor(Math.random() * lowercase.length)];
142-
password += numbers[Math.floor(Math.random() * numbers.length)];
143-
password += symbols[Math.floor(Math.random() * symbols.length)];
144-
145-
// Fill the rest randomly
146-
for (let i = password.length; i < length; i++) {
147-
password += alphabet[Math.floor(Math.random() * alphabet.length)];
130+
setLoading(prev => ({ ...prev, password: true }));
131+
try {
132+
const length = passwordLength;
133+
const uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
134+
const lowercase = 'abcdefghijklmnopqrstuvwxyz';
135+
const numbers = '0123456789';
136+
const symbols = '!@#$%^&*()_+-=[]{}|;:,.<>?';
137+
138+
let charset = lowercase;
139+
if (includeUppercase) charset += uppercase;
140+
if (includeNumbers) charset += numbers;
141+
if (includeSymbols) charset += symbols;
142+
143+
let password = '';
144+
// Ensure at least one character from each selected type
145+
if (includeUppercase) password += uppercase[Math.floor(Math.random() * uppercase.length)];
146+
password += lowercase[Math.floor(Math.random() * lowercase.length)];
147+
if (includeNumbers) password += numbers[Math.floor(Math.random() * numbers.length)];
148+
if (includeSymbols) password += symbols[Math.floor(Math.random() * symbols.length)];
149+
150+
// Fill the rest randomly
151+
while (password.length < length) {
152+
password += charset[Math.floor(Math.random() * charset.length)];
153+
}
154+
155+
// Shuffle the password
156+
password = password.split('').sort(() => Math.random() - 0.5).join('');
157+
158+
setPassword(password);
159+
} catch (error) {
160+
console.error('Password Generation Error:', error);
161+
setCopyFeedback('Failed to generate password');
162+
} finally {
163+
setLoading(prev => ({ ...prev, password: false }));
148164
}
149-
150-
// Shuffle the password
151-
password = password.split('').sort(() => Math.random() - 0.5).join('');
152-
153-
setPassword(password);
154-
setIsPasswordLoading(false);
155165
};
156166

157167
const downloadKeys = () => {

0 commit comments

Comments
 (0)