-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
707 lines (619 loc) · 26.8 KB
/
index.html
File metadata and controls
707 lines (619 loc) · 26.8 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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<title>Partage sécurisé de texte</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
:root {
--background: 0 0% 100%;
--foreground: 240 10% 3.9%;
--card: 0 0% 100%;
--card-foreground: 240 10% 3.9%;
--popover: 0 0% 100%;
--popover-foreground: 240 10% 3.9%;
--primary: 240 5.9% 10%;
--primary-foreground: 0 0% 98%;
--secondary: 240 4.8% 95.9%;
--secondary-foreground: 240 5.9% 10%;
--muted: 240 4.8% 95.9%;
--muted-foreground: 240 3.8% 46.1%;
--accent: 240 4.8% 95.9%;
--accent-foreground: 240 5.9% 10%;
--destructive: 0 84.2% 60.2%;
--destructive-foreground: 0 0% 98%;
--border: 240 5.9% 90%;
--input: 240 5.9% 90%;
--ring: 240 5.9% 10%;
--radius: 0.5rem;
}
html {
background-color: hsl(var(--background));
color: hsl(var(--foreground));
}
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
max-width: 600px;
margin: 2rem auto;
padding: 1rem;
}
#app-container {
background: hsl(var(--card));
color: hsl(var(--card-foreground));
border-radius: var(--radius);
border: 1px solid hsl(var(--border));
padding: 2rem;
}
h1 {
font-size: 1.875rem;
font-weight: 800;
letter-spacing: -0.025em;
text-align: center;
margin-bottom: 2rem;
}
h2 {
font-size: 1.5rem;
font-weight: 600;
letter-spacing: -0.025em;
border-bottom: 1px solid hsl(var(--border));
padding-bottom: 0.5rem;
margin-bottom: 1.5rem;
}
h3 {
font-size: 1.125rem;
font-weight: 600;
margin-top: 1.5rem;
margin-bottom: 0.5rem;
}
textarea, input, select {
width: 100%;
margin: 0.5rem 0;
padding: 0.75rem 1rem;
font-size: 1rem;
background-color: hsl(var(--input));
border: 1px solid hsl(var(--border));
border-radius: calc(var(--radius) - 2px);
color: hsl(var(--foreground));
box-sizing: border-box;
transition: all 0.2s;
}
textarea:focus, input:focus, select:focus {
outline: 2px solid hsl(var(--ring));
outline-offset: 2px;
}
button {
display: inline-flex;
align-items: center;
justify-content: center;
width: 100%;
margin-top: 1rem;
padding: 0.75rem 1.2rem;
font-size: 1rem;
font-weight: 600;
cursor: pointer;
border-radius: calc(var(--radius) - 2px);
border: none;
background-color: hsl(var(--primary));
color: hsl(var(--primary-foreground));
transition: background-color 0.2s;
}
button:hover {
background-color: hsl(var(--primary) / 0.9);
}
pre {
background: hsl(var(--secondary));
padding: 1rem;
border-radius: var(--radius);
word-break: break-all;
white-space: pre-wrap;
font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, Courier, monospace;
color: hsl(var(--secondary-foreground));
}
label {
display: block;
font-size: 0.875rem;
font-weight: 500;
margin-top: 1rem;
color: hsl(var(--muted-foreground));
}
</style>
</head>
<body>
<h1>🔒 Partage sécurisé de texte</h1>
<div id="app-container">
<div id="app"></div>
</div>
<script>
// --- Utils ---
function bufToBase64(buf) {
return btoa(String.fromCharCode(...new Uint8Array(buf)));
}
function base64ToBuf(b64) {
return Uint8Array.from(atob(b64), c => c.charCodeAt(0));
}
// Fonction pour obtenir l'heure du serveur avec vérification de domaine
async function getServerTime() {
try {
// 1. Vérifier que nous sommes bien sur GitHub Pages ou un domaine approuvé
const currentDomain = window.location.hostname;
const approvedDomains = [
'github.io', // GitHub Pages
'githubusercontent.com', // GitHub raw content
'pages.github.com', // GitHub Pages
'frntn.github.io' // Votre domaine GitHub Pages spécifique
];
let isDomainApproved = false;
for (const domain of approvedDomains) {
if (currentDomain === domain || currentDomain.endsWith('.' + domain)) {
isDomainApproved = true;
break;
}
}
if (!isDomainApproved) {
console.warn("Domaine non approuvé pour la récupération de l'heure:", currentDomain);
throw new Error("Domaine non approuvé");
}
// 2. Récupérer l'heure du serveur via la requête HEAD
const response = await fetch(window.location.href, {
method: 'HEAD',
cache: 'no-store' // Empêcher la mise en cache qui pourrait fournir une ancienne date
});
if (!response.ok) throw new Error("Erreur lors de la récupération de l'heure du serveur");
// 3. Vérifier que la réponse vient bien de GitHub
const serverHeader = response.headers.get('server');
if (!serverHeader || !serverHeader.toLowerCase().includes('github')) {
console.warn("En-tête de serveur non reconnu:", serverHeader);
throw new Error("Serveur non reconnu");
}
// 4. Récupération de la date
const serverDate = response.headers.get('date');
if (!serverDate) throw new Error("L'en-tête 'date' est manquant dans la réponse du serveur");
return new Date(serverDate).getTime(); // Convertir en timestamp
} catch (error) {
console.warn("Impossible d'obtenir l'heure du serveur:", error);
return null; // En cas d'échec, on retournera null
}
}
// Fonction pour obtenir l'heure depuis plusieurs sources externes et faire un consensus
async function getConsensusTime() {
try {
// Liste de services d'horloge publics qui supportent CORS
const timeServices = [
"https://worldtimeapi.org/api/ip", // World Time API
"https://worldclockapi.com/api/json/utc/now", // World Clock API
"https://timeapi.io/api/Time/current/zone?timeZone=UTC" // Time API
];
// Fonction pour extraire l'heure de chaque API
const extractTime = async (url) => {
try {
const response = await fetch(url, { cache: 'no-store' });
if (!response.ok) throw new Error(`Erreur ${response.status}`);
const data = await response.json();
// Chaque API a un format différent, nous devons adapter l'extraction
if (url.includes('worldtimeapi')) {
return new Date(data.utc_datetime).getTime();
} else if (url.includes('worldclockapi')) {
return new Date(data.currentDateTime).getTime();
} else if (url.includes('timeapi.io')) {
return new Date(data.dateTime).getTime();
}
return null;
} catch (e) {
console.warn(`Erreur avec ${url}:`, e);
return null;
}
};
// Récupérer l'heure depuis GitHub Pages également
const githubTime = await getServerTime();
// Récupérer l'heure depuis les services externes
const timePromises = timeServices.map(extractTime);
const times = await Promise.all(timePromises);
// Filtrer les résultats null et ajouter l'heure GitHub si disponible
const validTimes = times.filter(time => time !== null);
if (githubTime) validTimes.push(githubTime);
if (validTimes.length === 0) {
console.warn("Aucune source de temps valide disponible");
return null;
}
// Algorithme de consensus simple : utiliser la médiane des temps disponibles
// pour résister aux valeurs aberrantes
validTimes.sort((a, b) => a - b);
const medianIndex = Math.floor(validTimes.length / 2);
const consensusTime = validTimes[medianIndex];
console.log("Sources de temps consultées:", validTimes.length);
console.log("Temps médian retenu:", new Date(consensusTime).toISOString());
return consensusTime;
} catch (error) {
console.warn("Erreur lors de l'obtention du consensus temporel:", error);
return null;
}
}
// Dérivation des clés
async function deriveKeys(password, saltAes, saltHmac, iterations) {
// Transformer le mot de passe en clé cryptographique
const enc = new TextEncoder();
const pwKey = enc.encode(password);
const keyMaterial = await crypto.subtle.importKey(
"raw",
pwKey,
{ name: "PBKDF2" },
false,
["deriveKey"]
);
// Clé pour le chiffrement AES
const encKey = await crypto.subtle.deriveKey(
{ name: "PBKDF2", salt: saltAes, iterations: iterations, hash: "SHA-256" },
keyMaterial,
{ name: "AES-GCM", length: 256 },
false,
["encrypt", "decrypt"]
);
// Clé pour la signature HMAC
const signKey = await crypto.subtle.deriveKey(
{ name: "PBKDF2", salt: saltHmac, iterations: iterations, hash: "SHA-256" },
keyMaterial,
{ name: "HMAC", hash: "SHA-256" },
false,
["sign", "verify"]
);
return { encKey, signKey };
}
async function encryptText(text, password, expMinutes, iterations = 100000) {
const enc = new TextEncoder();
// Génération de sels aléatoires
const saltAes = crypto.getRandomValues(new Uint8Array(16));
const saltHmac = crypto.getRandomValues(new Uint8Array(16));
const { encKey, signKey } = await deriveKeys(password, saltAes, saltHmac, iterations);
const iv = crypto.getRandomValues(new Uint8Array(12));
const ciphertext = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, encKey, enc.encode(text));
// Essayer d'obtenir l'heure par consensus, puis l'heure du serveur, puis l'heure locale
let now = await getConsensusTime();
let timeSource = "consensus";
if (!now) {
now = await getServerTime();
timeSource = now ? "serveur" : "locale";
if (!now) {
now = Date.now();
}
}
const iat = now;
const exp = iat + expMinutes * 60 * 1000;
const payload = JSON.stringify({
iv: Array.from(iv),
data: bufToBase64(ciphertext),
saltAes: Array.from(saltAes),
saltHmac: Array.from(saltHmac),
iterations: iterations,
iat,
exp,
timeSource: timeSource // Indiquer la source du timestamp
});
const signature = await crypto.subtle.sign("HMAC", signKey, enc.encode(payload));
return btoa(JSON.stringify({
p: payload,
s: bufToBase64(signature)
}));
}
async function decryptText(b64, password) {
const { p: payloadStr, s: signatureB64 } = JSON.parse(atob(b64));
const payload = JSON.parse(payloadStr);
// Récupération des sels et nombre d'itérations du payload
const saltAes = new Uint8Array(payload.saltAes);
const saltHmac = new Uint8Array(payload.saltHmac);
const iterations = payload.iterations || 100000;
const { encKey, signKey } = await deriveKeys(password, saltAes, saltHmac, iterations);
const signature = base64ToBuf(signatureB64);
const isValid = await crypto.subtle.verify("HMAC", signKey, signature, new TextEncoder().encode(payloadStr));
if (!isValid) {
throw new Error("🚫 Signature invalide. Les données ont peut-être été altérées.");
}
// Essayer d'obtenir l'heure par consensus, puis l'heure du serveur, puis l'heure locale
let now = await getConsensusTime();
let timeSource = "consensus";
if (!now) {
now = await getServerTime();
timeSource = now ? "serveur" : "locale";
if (!now) {
now = Date.now();
}
}
const creationTime = new Date(payload.iat);
const expirationTime = new Date(payload.exp);
// Vérification plus détaillée des dates
if (now < payload.iat) {
throw new Error(`⏳ Ce message n'est pas encore valide. Veuillez réessayer plus tard.`);
}
if (now > payload.exp) {
throw new Error(`⏰ Ce lien a expiré et n'est plus accessible. Veuillez demander un nouveau lien au créateur du message.`);
}
// Si nous sommes ici, les vérifications temporelles sont passées
const iv = new Uint8Array(payload.iv);
const ciphertext = base64ToBuf(payload.data);
const plaintext = await crypto.subtle.decrypt({ name: "AES-GCM", iv }, encKey, ciphertext);
// Calculer le temps restant avant expiration
const textWithTimeInfo = new TextDecoder().decode(plaintext) +
`\n\n---\nCe message est actuellement valide.\nVérification effectuée via l'horloge ${timeSource}.`;
return textWithTimeInfo;
}
// --- UI ---
function showCreator() {
document.getElementById("app").innerHTML = `
<h2>Créer un lien</h2>
<form id="encrypt-form" onsubmit="return false;">
<textarea id="msg" rows="6" placeholder="Écrivez votre message secret ici..."></textarea>
<input type="password" id="pw" placeholder="Mot de passe">
<div id="pw-strength" style="height: 5px; width: 100%; background: #f0f0f0; margin-bottom: 10px;"></div>
<div id="pw-feedback" style="font-size: 0.8rem; color: hsl(var(--muted-foreground)); margin-bottom: 10px;"></div>
<label for="exp">Durée d'expiration</label>
<select id="exp">
<option value="10">10 minutes</option>
<option value="60">1 heure</option>
<option value="1440">24 heures</option>
<option value="10080">7 jours</option>
</select>
<details>
<summary style="cursor: pointer; margin: 1rem 0; color: hsl(var(--muted-foreground));">Paramètres de sécurité avancés</summary>
<div style="padding: 1rem; background: hsl(var(--secondary)); border-radius: var(--radius); margin-bottom: 1rem;">
<label for="iterations">Nombre d'itérations PBKDF2</label>
<select id="iterations">
<option value="100000">Standard (100,000 itérations)</option>
<option value="200000">Renforcé (200,000 itérations)</option>
<option value="500000">Haute sécurité (500,000 itérations)</option>
</select>
<p style="font-size: 0.8rem; color: hsl(var(--muted-foreground));">Un nombre d'itérations plus élevé renforce la sécurité mais peut ralentir le chiffrement/déchiffrement.</p>
</div>
</details>
<button type="submit" id="go">Générer le lien</button>
</form>
<h3>Lien sécurisé :</h3>
<pre id="out"></pre>
<div id="loading" style="display: none; text-align: center; margin: 1rem 0;">
<div style="display: inline-block; width: 20px; height: 20px; border: 3px solid hsl(var(--secondary)); border-radius: 50%; border-top-color: hsl(var(--primary)); animation: spin 1s linear infinite;"></div>
<p style="margin-top: 0.5rem; color: hsl(var(--muted-foreground));">
Chiffrement en cours... <span id="timer">0s</span>
</p>
</div>
<div id="time-notice" style="margin-top: 1rem; padding: 0.75rem; background: hsl(var(--secondary)); border-radius: var(--radius); font-size: 0.9rem; display: none;"></div>
`;
// Vérification de la force du mot de passe
const pwInput = document.getElementById("pw");
const pwStrength = document.getElementById("pw-strength");
const pwFeedback = document.getElementById("pw-feedback");
pwInput.addEventListener("input", function() {
checkPasswordStrength(this.value);
});
function checkPasswordStrength(password) {
let strength = 0;
let feedback = [];
if (password.length === 0) {
pwStrength.style.width = "0%";
pwStrength.style.background = "#f0f0f0";
pwFeedback.textContent = "";
return;
}
// Longueur
if (password.length < 8) {
feedback.push("Le mot de passe devrait contenir au moins 8 caractères.");
} else {
strength += 25;
}
// Contient des chiffres
if (/\d/.test(password)) {
strength += 25;
} else {
feedback.push("Ajoutez des chiffres.");
}
// Contient des minuscules et majuscules
if (/[a-z]/.test(password) && /[A-Z]/.test(password)) {
strength += 25;
} else {
feedback.push("Ajoutez des lettres majuscules et minuscules.");
}
// Contient des caractères spéciaux
if (/[^a-zA-Z0-9]/.test(password)) {
strength += 25;
} else {
feedback.push("Ajoutez des caractères spéciaux.");
}
// Mettre à jour la barre de progression
pwStrength.style.width = strength + "%";
// Couleur de la barre basée sur la force
if (strength < 50) {
pwStrength.style.background = "#FF4136"; // Rouge
} else if (strength < 75) {
pwStrength.style.background = "#FFDC00"; // Jaune
} else {
pwStrength.style.background = "#2ECC40"; // Vert
}
// Afficher le feedback
pwFeedback.innerHTML = feedback.length > 0 ? feedback.join("<br>") : "Mot de passe de force acceptable.";
}
// Récupérer les éléments du DOM pour l'animation et l'interaction
const encryptForm = document.getElementById("encrypt-form");
const generateButton = document.getElementById("go");
const messageInput = document.getElementById("msg");
const passwordInput = document.getElementById("pw");
const loadingIndicator = document.getElementById("loading");
const outputElement = document.getElementById("out");
const performEncryption = async () => {
const msg = messageInput.value.trim();
const pw = passwordInput.value.trim();
const exp = parseInt(document.getElementById("exp").value);
const iterations = parseInt(document.getElementById("iterations").value);
if (!msg) {
alert("⚠️ Le message ne peut pas être vide !");
return;
}
if (!pw) {
alert("⚠️ Le mot de passe est obligatoire !");
return;
}
// Vérification de la force minimale du mot de passe
if (pw.length < 8) {
if (!confirm("⚠️ Votre mot de passe est trop court (moins de 8 caractères). Continuer quand même ?")) {
return;
}
}
try {
// Désactiver les contrôles et afficher l'animation de chargement
generateButton.disabled = true;
messageInput.disabled = true;
passwordInput.disabled = true;
document.getElementById("exp").disabled = true;
document.getElementById("iterations").disabled = true;
loadingIndicator.style.display = "block";
outputElement.textContent = "Génération du lien sécurisé...";
// Démarrer le compteur de temps
const timerElement = document.getElementById("timer");
let seconds = 0;
const timer = setInterval(() => {
seconds++;
timerElement.textContent = seconds + "s";
}, 1000);
// Petit délai pour que l'interface se mette à jour avant le traitement intensif
await new Promise(resolve => setTimeout(resolve, 50));
// Vérification préalable de l'horloge consensus
const consensusTime = await getConsensusTime();
let timeNotice = "";
if (consensusTime) {
const consensusDate = new Date(consensusTime);
const localDate = new Date();
const diffMinutes = Math.round(Math.abs(consensusTime - Date.now()) / (60 * 1000));
if (diffMinutes > 5) {
timeNotice = `⚠️ Attention : l'horloge de votre appareil (${localDate.toLocaleTimeString()}) ` +
`diffère de l'horloge consensus (${consensusDate.toLocaleTimeString()}) de ${diffMinutes} minutes. ` +
`L'horloge consensus sera utilisée comme référence temporelle.`;
} else {
timeNotice = `ℹ️ L'horloge consensus (${consensusDate.toLocaleTimeString()}) sera utilisée comme référence temporelle.`;
}
} else {
// Si le consensus échoue, essayer l'horloge du serveur
const serverTime = await getServerTime();
if (serverTime) {
const serverDate = new Date(serverTime);
const localDate = new Date();
const diffMinutes = Math.round(Math.abs(serverTime - Date.now()) / (60 * 1000));
if (diffMinutes > 5) {
timeNotice = `⚠️ Attention : l'horloge de votre appareil (${localDate.toLocaleTimeString()}) ` +
`diffère de celle du serveur (${serverDate.toLocaleTimeString()}) de ${diffMinutes} minutes. ` +
`L'horloge du serveur sera utilisée comme référence temporelle.`;
} else {
timeNotice = `ℹ️ L'horloge du serveur (${serverDate.toLocaleTimeString()}) sera utilisée comme référence temporelle.`;
}
} else {
timeNotice = "⚠️ Impossible d'obtenir l'heure de référence. L'horloge locale sera utilisée, ce qui présente un risque si elle est incorrecte.";
}
}
const b64 = await encryptText(msg, pw, exp, iterations);
const secureLink = location.origin + location.pathname + "#data=" + b64;
outputElement.textContent = secureLink;
document.getElementById("time-notice").innerHTML = timeNotice;
document.getElementById("time-notice").style.display = "block";
} catch (e) {
outputElement.textContent = "Erreur : " + e.message;
} finally {
// Arrêter le compteur
clearInterval(timer);
// Réactiver les contrôles et masquer l'animation de chargement
generateButton.disabled = false;
messageInput.disabled = false;
passwordInput.disabled = false;
document.getElementById("exp").disabled = false;
document.getElementById("iterations").disabled = false;
loadingIndicator.style.display = "none";
}
};
// Associer la fonction aux événements
generateButton.onclick = performEncryption;
encryptForm.onsubmit = (e) => {
e.preventDefault();
performEncryption();
};
}
function showReader(b64) {
document.getElementById("app").innerHTML = `
<h2>Lire un message</h2>
<p style="color: hsl(var(--muted-foreground)); font-size: 0.9rem;">Ce lien contient un texte chiffré. Entrez le mot de passe pour le révéler.</p>
<form id="decrypt-form" onsubmit="return false;">
<input type="password" id="pw" placeholder="Mot de passe">
<button type="submit" id="dec">Déchiffrer</button>
</form>
<h3>Résultat :</h3>
<pre id="out"></pre>
<div id="loading" style="display: none; text-align: center; margin: 1rem 0;">
<div style="display: inline-block; width: 20px; height: 20px; border: 3px solid hsl(var(--secondary)); border-radius: 50%; border-top-color: hsl(var(--primary)); animation: spin 1s linear infinite;"></div>
<p style="margin-top: 0.5rem; color: hsl(var(--muted-foreground));">
Déchiffrement en cours... <span id="timer">0s</span>
</p>
</div>
`;
// Ajouter l'animation de chargement en CSS
if (!document.getElementById('spin-animation')) {
const style = document.createElement('style');
style.id = 'spin-animation';
style.textContent = `
@keyframes spin {
to { transform: rotate(360deg); }
}
`;
document.head.appendChild(style);
}
// Gérer à la fois le clic sur le bouton et la touche Entrée
const decryptForm = document.getElementById("decrypt-form");
const decryptButton = document.getElementById("dec");
const passwordInput = document.getElementById("pw");
const loadingIndicator = document.getElementById("loading");
const outputElement = document.getElementById("out");
const performDecryption = async () => {
const pw = passwordInput.value.trim();
if (!pw) {
alert("⚠️ Veuillez entrer un mot de passe.");
return;
}
// Afficher l'indicateur de chargement
loadingIndicator.style.display = "block";
outputElement.textContent = "";
decryptButton.disabled = true;
passwordInput.disabled = true;
// Démarrer le compteur de temps
const timerElement = document.getElementById("timer");
let seconds = 0;
const timer = setInterval(() => {
seconds++;
timerElement.textContent = seconds + "s";
}, 1000);
try {
// Petit délai pour que l'interface se mette à jour avant le traitement intensif
await new Promise(resolve => setTimeout(resolve, 50));
const txt = await decryptText(b64, pw);
outputElement.textContent = txt;
} catch (e) {
outputElement.textContent = "Erreur : " + e.message;
} finally {
// Arrêter le compteur
clearInterval(timer);
// Masquer l'indicateur de chargement quoi qu'il arrive
loadingIndicator.style.display = "none";
decryptButton.disabled = false;
passwordInput.disabled = false;
passwordInput.focus();
}
};
// Associer la fonction aux événements
decryptButton.onclick = performDecryption;
decryptForm.onsubmit = (e) => {
e.preventDefault();
performDecryption();
};
// Mettre le focus sur le champ de mot de passe au chargement
passwordInput.focus();
}
// --- Init ---
if (location.hash.startsWith("#data=")) {
showReader(location.hash.slice(6));
} else {
showCreator();
}
</script>
</body>
</html>