-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
362 lines (301 loc) · 14.2 KB
/
script.js
File metadata and controls
362 lines (301 loc) · 14.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
const passwordInput = document.getElementById('passwordInput');
const togglePassword = document.getElementById('togglePassword');
const strengthBar = document.getElementById('strengthBar');
const strengthMessage = document.getElementById('strengthMessage');
const pwnedMessage = document.getElementById('pwnedMessage');
const analyzeCard = document.getElementById('analyzeCard');
const copyPassword = document.getElementById('copyPassword');
const crackTimeMessage = document.getElementById('crackTimeMessage');
const historyCard = document.getElementById('historyCard');
const passwordHistoryList = document.getElementById('passwordHistory');
let passwordHistory = [];
// Generator elements
const lengthSlider = document.getElementById('lengthSlider');
const lengthValue = document.getElementById('lengthValue');
const incUppercase = document.getElementById('incUppercase');
const incLowercase = document.getElementById('incLowercase');
const incNumbers = document.getElementById('incNumbers');
const incSymbols = document.getElementById('incSymbols');
const generateBtn = document.getElementById('generateBtn');
const memorableKeyword = document.getElementById('memorableKeyword');
let pwnedCheckTimeout;
// SVGs for eye icon
const eyeOpenSVG = `<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-eye"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></svg>`;
const eyeClosedSVG = `<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-eye-off"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"></path><line x1="1" y1="1" x2="23" y2="23"></line></svg>`;
// Live feedback on password strength
passwordInput.addEventListener('input', function () {
const password = passwordInput.value;
if (password.length === 0) {
strengthBar.style.width = '0%';
strengthMessage.textContent = 'Waiting for input...';
strengthMessage.style.color = 'var(--text-muted)';
pwnedMessage.style.display = 'none';
analyzeCard.style.backgroundColor = 'var(--card-bg)';
return;
}
const analysis = analyzePassword(password);
updateStrengthUI(analysis);
// Debounce the Pwned check API call
clearTimeout(pwnedCheckTimeout);
pwnedMessage.style.display = 'none';
if (password.length >= 6) {
pwnedCheckTimeout = setTimeout(() => {
checkPwnedPassword(password);
}, 500);
}
});
// Toggle password visibility
togglePassword.addEventListener('click', function () {
const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
passwordInput.setAttribute('type', type);
togglePassword.innerHTML = type === 'password' ? eyeOpenSVG : eyeClosedSVG;
});
// Update slider value display
lengthSlider.addEventListener('input', function () {
lengthValue.textContent = this.value;
});
// Copy to clipboard
copyPassword.addEventListener('click', function() {
const pwd = passwordInput.value;
if (!pwd) return;
navigator.clipboard.writeText(pwd).then(() => {
const originalSvg = copyPassword.innerHTML;
copyPassword.innerHTML = `<span style="font-size: 12px; font-weight: 600; color: var(--strength-strong);">Copied!</span>`;
setTimeout(() => {
copyPassword.innerHTML = originalSvg;
}, 1500);
});
});
// Generate password
generateBtn.addEventListener('click', async function(e) {
e.preventDefault();
let length = parseInt(lengthSlider.value);
const keyword = memorableKeyword.value.trim();
if (length < 12) {
length = 12;
lengthSlider.value = 12;
lengthValue.textContent = '12';
alert('Minimum password length enforced to 12 characters for cryptographic security.');
}
const hasUpper = incUppercase.checked;
const hasLower = incLowercase.checked;
const hasNumbers = incNumbers.checked;
const hasSymbols = incSymbols.checked;
if (!hasUpper && !hasLower && !hasNumbers && !hasSymbols && keyword.length === 0) {
alert('Please select at least one character type or provide a keyword.');
return;
}
if (keyword.length > length) {
// Warning no longer needed since keyword is hashed, not appended
}
const newPassword = await generateSecurePassword(length, keyword, hasUpper, hasLower, hasNumbers, hasSymbols);
passwordInput.value = newPassword;
passwordInput.setAttribute('type', 'text');
togglePassword.innerHTML = eyeClosedSVG;
// Add to history
passwordHistory.unshift(newPassword);
if (passwordHistory.length > 5) passwordHistory.pop();
// Render history
historyCard.style.display = 'block';
passwordHistoryList.innerHTML = passwordHistory.map(pwd => `<li style="padding: 6px; background: rgba(0,0,0,0.03); border-radius: 4px;">${pwd.replace(/</g, "<")}</li>`).join('');
// Trigger input event to re-analyze
passwordInput.dispatchEvent(new Event('input'));
});
function analyzePassword(password) {
const length = password.length;
let poolSize = 0;
if (/[a-z]/.test(password)) poolSize += 26;
if (/[A-Z]/.test(password)) poolSize += 26;
if (/[0-9]/.test(password)) poolSize += 10;
if (/[^a-zA-Z0-9]/.test(password)) poolSize += 32;
let entropy = poolSize === 0 ? 0 : length * Math.log2(poolSize);
let crackTime = getCrackTimeFromChart(password);
let strength = 'Weak';
const isMixed = poolSize >= 36; // At least letters + numbers or mixed letters
if (isMixed) {
if (length >= 16) strength = 'Very Strong';
else if (length >= 12) strength = 'Strong';
else if (length >= 8) strength = 'Moderate';
else strength = 'Weak';
} else {
if (length >= 16) strength = 'Strong';
else if (length >= 10) strength = 'Moderate';
else strength = 'Weak';
}
let score = Math.min(100, (entropy / 100) * 100);
let feedback = [];
if (entropy < 70 && length > 0) {
feedback.push('Target entropy is > 70 bits. Increase length or diversity.');
}
return { score, strength, feedback, crackTime, entropy };
}
function updateStrengthUI(analysis) {
strengthBar.style.width = analysis.score + '%';
let color = 'var(--strength-weak)';
let text = 'Weak';
let bgColor = 'rgba(239, 68, 68, 0.1)';
if (analysis.strength === 'Very Strong') {
color = '#2563eb';
text = 'Very Strong';
bgColor = 'rgba(37, 99, 235, 0.1)';
strengthBar.style.width = '100%';
} else if (analysis.strength === 'Strong') {
color = 'var(--strength-strong)';
text = 'Strong';
bgColor = 'rgba(16, 185, 129, 0.1)';
} else if (analysis.strength === 'Moderate') {
color = 'var(--strength-medium)';
text = 'Moderate';
bgColor = 'rgba(245, 158, 11, 0.1)';
}
strengthBar.style.backgroundColor = color;
analyzeCard.style.backgroundColor = bgColor;
let messageHtml = `<div style="display: flex; justify-content: space-between; align-items: center; width: 100%;">
<span><strong>Strength: ${text}</strong></span>
<span style="font-size: 13px; font-family: monospace; color: var(--text-muted);">Entropy: ${analysis.entropy ? analysis.entropy.toFixed(1) : 0} bits</span>
</div>`;
if (analysis.feedback && analysis.feedback.length > 0 && analysis.strength !== 'Very Strong') {
messageHtml += `<div style="margin-top: 5px; font-size: 13px;">Tip: ${analysis.feedback[0]}</div>`;
}
strengthMessage.innerHTML = messageHtml;
strengthMessage.style.color = color;
if (analysis.crackTime) {
crackTimeMessage.innerHTML = `⏱️ Estimated time to crack: <strong style="color: var(--text-main);">${analysis.crackTime}</strong>`;
} else {
crackTimeMessage.innerHTML = '';
}
}
function getCrackTimeFromChart(password) {
const length = password.length;
if (length === 0) return '';
let poolSize = 0;
if (/[a-z]/.test(password)) poolSize += 26;
if (/[A-Z]/.test(password)) poolSize += 26;
if (/[0-9]/.test(password)) poolSize += 10;
if (/[^a-zA-Z0-9]/.test(password)) poolSize += 32;
let col = 0;
if (poolSize <= 10) col = 0; // Numbers only
else if (poolSize <= 26) col = 1; // Lowercase or Uppercase only
else if (poolSize <= 52) col = 2; // Mixed letters
else if (poolSize <= 62) col = 3; // Letters + Numbers
else col = 4; // Letters + Numbers + Symbols
const chart = [
["Instantly", "Instantly", "Instantly", "Instantly", "Instantly"], // 4
["Instantly", "Instantly", "57 minutes", "2 hours", "4 hours"], // 5
["Instantly", "46 minutes", "2 days", "6 days", "2 weeks"], // 6
["Instantly", "20 hours", "4 months", "1 year", "2 years"], // 7
["Instantly", "3 weeks", "15 years", "62 years", "164 years"], // 8
["2 hours", "2 years", "791 years", "3k years", "11k years"], // 9
["1 day", "40 years", "41k years", "238k years", "803k years"], // 10
["1 weeks", "1k years", "2m years", "14m years", "56m years"], // 11
["3 months", "27k years", "111m years", "917m years", "3bn years"],// 12
["3 years", "705k years", "5bn years", "56bn years", "275bn years"],// 13
["28 years", "18m years", "300bn years", "3tn years", "19tn years"],// 14
["284 years", "477m years", "15tn years", "218tn years", "1qd years"],// 15
["2k years", "12bn years", "812tn years", "13qd years", "94qd years"],// 16
["28k years", "322bn years", "42qd years", "840qd years", "6qn years"],// 17
["284k years", "8tn years", "2qn years", "52qn years", "463qn years"] // 18
];
if (length <= 4) return chart[0][col];
if (length >= 18) {
if (length === 18) return chart[14][col];
if (col === 0) return "284k+ years";
if (col === 1) return "8tn+ years";
if (col === 2) return "2qn+ years";
if (col === 3) return "52qn+ years";
if (col === 4) return "463qn+ years";
}
return chart[length - 4][col];
}
async function generateSecurePassword(length, keyword, upper, lower, numbers, symbols) {
const charset = {
upper: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
lower: 'abcdefghijklmnopqrstuvwxyz',
numbers: '0123456789',
symbols: '!@#$%^&*()_+~`|}{[]:;?><,./-='
};
let allowedChars = '';
if (!upper && !lower && !numbers && !symbols) {
lower = true;
numbers = true;
}
if (upper) allowedChars += charset.upper;
if (lower) allowedChars += charset.lower;
if (numbers) allowedChars += charset.numbers;
if (symbols) allowedChars += charset.symbols;
// We need random values for generation (length) + shuffle (length) + guarantees (up to 4)
const randomValues = new Uint32Array(length * 3);
window.crypto.getRandomValues(randomValues);
let hashBytes = new Uint8Array(0);
if (keyword.length > 0) {
const buffer = new TextEncoder().encode(keyword);
const hashBuffer = await crypto.subtle.digest("SHA-256", buffer);
hashBytes = new Uint8Array(hashBuffer);
}
let valIndex = 0;
const getMixedValue = () => {
let val = randomValues[valIndex++];
if (hashBytes.length > 0) {
val = (val ^ hashBytes[valIndex % hashBytes.length]) >>> 0;
}
return val;
};
let passwordArr = [];
// Guarantee inclusion of all selected character categories
if (upper) passwordArr.push(charset.upper[getMixedValue() % charset.upper.length]);
if (lower) passwordArr.push(charset.lower[getMixedValue() % charset.lower.length]);
if (numbers) passwordArr.push(charset.numbers[getMixedValue() % charset.numbers.length]);
if (symbols) passwordArr.push(charset.symbols[getMixedValue() % charset.symbols.length]);
// Fill the remaining length with completely random characters
while (passwordArr.length < length) {
passwordArr.push(allowedChars[getMixedValue() % allowedChars.length]);
}
// CSPRNG-based Fisher-Yates shuffle to ensure no predictable pattern
for (let i = passwordArr.length - 1; i > 0; i--) {
const j = getMixedValue() % (i + 1);
[passwordArr[i], passwordArr[j]] = [passwordArr[j], passwordArr[i]];
}
return passwordArr.join('');
}
// HIBP API Integration
async function checkPwnedPassword(password) {
try {
const hash = await sha1(password);
const prefix = hash.substring(0, 5);
const suffix = hash.substring(5);
const response = await fetch(`https://api.pwnedpasswords.com/range/${prefix}`);
if (!response.ok) throw new Error('API Error');
const text = await response.text();
const lines = text.split('\n');
let isPwned = false;
let count = 0;
for (const line of lines) {
const [hashSuffix, matchCount] = line.split(':');
if (hashSuffix.trim() === suffix) {
isPwned = true;
count = parseInt(matchCount.trim(), 10);
break;
}
}
if (isPwned) {
pwnedMessage.style.display = 'block';
pwnedMessage.innerHTML = `⚠️ <strong>Warning!</strong> This password has been seen ${count.toLocaleString()} times in data breaches. Do not use it.`;
}
} catch (error) {
console.error('Error checking password:', error);
}
}
async function sha1(str) {
const buffer = new TextEncoder("utf-8").encode(str);
const hash = await crypto.subtle.digest("SHA-1", buffer);
const hexCodes = [];
const view = new DataView(hash);
for (let i = 0; i < view.byteLength; i += 4) {
const value = view.getUint32(i);
const stringValue = value.toString(16);
const padding = '00000000';
const paddedValue = (padding + stringValue).slice(-padding.length);
hexCodes.push(paddedValue);
}
return hexCodes.join("").toUpperCase();
}