-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
640 lines (575 loc) · 29.6 KB
/
index.html
File metadata and controls
640 lines (575 loc) · 29.6 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
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="本地文本加解密工具,使用Argon2id和PBKDF2">
<title>加密锁CryptoLock - 本地安全加密工具</title>
<style>
:root {
--bg: #f6f8fb; --card: #fff; --accent: #2563eb; --accent-hover: #1d4ed8; --secondary: #0ea5e9;
--ok: #16a34a; --danger: #dc2626; --warning: #f59e0b; --muted: #6b7280; --border: #e6eef8;
--text: #0f172a; --radius: 12px; --shadow: 0 8px 30px rgba(2, 6, 23, 0.08); --transition: all 0.2s ease;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #0f172a; --card: #1e293b; --accent: #3b82f6; --accent-hover: #2563eb; --secondary: #38bdf8;
--ok: #22c55e; --danger: #ef4444; --warning: #f59e0b; --muted: #94a3b8; --border: #334155; --text: #f1f5f9;
}
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: 'Inter', system-ui, -apple-system, 'Segoe UI', Roboto, Arial, sans-serif;
background: var(--bg); color: var(--text); line-height: 1.6; min-height: 100vh; padding: 20px; }
.wrap { max-width: 1000px; margin: 0 auto; background: var(--card); padding: 28px;
border-radius: var(--radius); box-shadow: var(--shadow); }
header { display: flex; align-items: center; gap: 12px; margin-bottom: 16px; padding-bottom: 16px; border-bottom: 2px solid var(--border); }
.header-icon { width: 28px; height: 28px; fill: var(--accent); }
h1 { font-size: 1.5rem; margin: 0; color: var(--text); display: flex; align-items: center; gap: 10px; }
.description { color: var(--muted); margin-bottom: 24px; font-size: 0.95rem; line-height: 1.7; }
.section { margin-bottom: 28px; }
.section-title { font-size: 1.1rem; margin-bottom: 12px; color: var(--text); font-weight: 600;
display: flex; align-items: center; gap: 8px; }
.section-title svg { width: 18px; height: 18px; fill: var(--accent); }
label { display: block; margin-bottom: 8px; font-weight: 600; font-size: 0.95rem; color: var(--text); }
textarea, input[type="password"], input[type="text"], select { width: 100%; padding: 14px;
border-radius: 8px; border: 2px solid var(--border); background: var(--card); color: var(--text);
font-family: inherit; font-size: 0.95rem; transition: var(--transition); resize: vertical; }
textarea:focus, input:focus, select:focus { outline: none; border-color: var(--accent);
box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1); }
textarea:hover, input:hover, select:hover { border-color: var(--accent); }
input[type="checkbox"] { width: auto; margin-right: 8px; }
.grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; margin-bottom: 20px; }
.card { background: var(--bg); padding: 20px; border-radius: 10px; border: 1px solid var(--border); }
.row { display: flex; gap: 12px; flex-wrap: wrap; margin-top: 16px; }
button { background: var(--accent); color: white; border: none; padding: 14px 20px; border-radius: 8px;
cursor: pointer; font-weight: 600; font-size: 0.95rem; transition: var(--transition);
display: inline-flex; align-items: center; gap: 8px; min-height: 48px; }
button:hover:not(:disabled) { background: var(--accent-hover); transform: translateY(-1px); }
button:disabled { opacity: 0.6; cursor: not-allowed; transform: none; }
button.secondary { background: transparent; color: var(--accent); border: 2px solid var(--border); }
button.secondary:hover:not(:disabled) { background: rgba(37, 99, 235, 0.1); border-color: var(--accent); }
.status { padding: 12px; border-radius: 8px; margin: 8px 0; font-size: 0.9rem; display: flex; align-items: center; gap: 8px; }
.status.ok { background: rgba(22, 163, 74, 0.1); color: var(--ok); border-left: 4px solid var(--ok); }
.status.info { background: rgba(14, 165, 233, 0.1); color: var(--secondary); border-left: 4px solid var(--secondary); }
.status.warning { background: rgba(245, 158, 11, 0.1); color: var(--warning); border-left: 4px solid var(--warning); }
.status.error { background: rgba(220, 38, 38, 0.1); color: var(--danger); border-left: 4px solid var(--danger); }
.kdf-info { font-size: 0.85rem; color: var(--muted); margin-top: 6px; line-height: 1.5; }
.password-group { display: flex; gap: 12px; align-items: center; }
.password-group input { flex: 1; }
.toggle-password { background: transparent; border: none; color: var(--muted); padding: 10px; cursor: pointer; min-height: auto; }
.toggle-password:hover { color: var(--text); background: var(--border); }
.strength-meter { height: 4px; background: var(--border); border-radius: 2px; margin-top: 8px; overflow: hidden; }
.strength-bar { height: 100%; width: 0%; transition: var(--transition); }
.strength-text { font-size: 0.8rem; margin-top: 4px; color: var(--muted); }
.output-container { position: relative; }
.output-actions { position: absolute; top: 10px; right: 10px; display: flex; gap: 8px; }
.output-btn { background: rgba(255, 255, 255, 0.9); border: 1px solid var(--border); border-radius: 4px;
padding: 6px 10px; font-size: 0.8rem; color: var(--text); cursor: pointer; }
.output-btn:hover { background: var(--accent); color: white; }
.tips { background: linear-gradient(135deg, rgba(14, 165, 233, 0.1), rgba(37, 99, 235, 0.05));
padding: 20px; border-radius: 10px; margin-top: 24px; }
.tips h3 { margin: 0 0 12px; color: var(--accent); font-size: 1.1rem; }
.tips ul { padding-left: 20px; }
.tips li { margin-bottom: 8px; color: var(--text); }
.loading { display: inline-block; width: 20px; height: 20px; border: 2px solid var(--border);
border-top-color: var(--accent); border-radius: 50%; animation: spin 1s linear infinite; }
.action-buttons { display: flex; flex-wrap: wrap; gap: 12px; margin: 20px 0; }
@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
@media (max-width: 768px) {
.wrap { padding: 16px; }
.grid { grid-template-columns: 1fr; }
.row, .action-buttons { flex-direction: column; }
button { width: 100%; justify-content: center; }
.password-group { flex-direction: column; align-items: stretch; }
}
</style>
</head>
<body>
<main class="wrap">
<header>
<svg class="header-icon" viewBox="0 0 24 24">
<path d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"/>
</svg>
<h1>加密锁CryptoLock - 本地安全加密工具</h1>
</header>
<p class="description">
优先使用Argon2(更安全)或回退到PBKDF2。支持一次性解密(防君子模式)。建议下载整套文件离线使用。
</p>
<section class="section">
<h2 class="section-title">
<svg viewBox="0 0 24 24"><path d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"/></svg>
加密设置
</h2>
<div class="grid">
<div class="card">
<label for="argonPreset">KDF 算法与预设</label>
<select id="argonPreset">
<option value="INTERACTIVE">Interactive (最快)</option>
<option value="MODERATE" selected>Moderate (推荐)</option>
<option value="SENSITIVE">Sensitive (更安全)</option>
</select>
<div class="kdf-info">
<span id="kdfStatus">检测中...</span>
<div style="margin-top: 8px;">
<button id="loadSodiumBtn" class="secondary" style="padding: 8px 12px; font-size: 0.85rem;">加载 libsodium</button>
</div>
</div>
</div>
<div class="card">
<div class="section-title">算法信息</div>
<div class="kdf-info">
<p><strong>Argon2id</strong>: 内存困难密码哈希函数</p>
<p><strong>PBKDF2</strong>: SHA-256密钥派生,200,000次迭代</p>
<p><strong>AES-GCM</strong>: 认证加密,256位密钥</p>
</div>
<div class="status info" id="algorithmInfo">
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
<path d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
</svg>
使用现代加密标准
</div>
</div>
<div class="card">
<div class="section-title">
<svg viewBox="0 0 24 24"><path d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"/></svg>
一次性解密(可选)
</div>
<div class="row" style="align-items: center; margin-bottom: 12px;">
<input type="checkbox" id="enableOneTime" style="width: auto; margin: 0;">
<label for="enableOneTime" style="display: inline; margin: 0; margin-left: 8px;">启用一次性解密(防君子模式)</label>
</div>
<div id="oneTimeSettings" style="display: none;">
<div class="kdf-info" style="margin-top: 12px;">
<p><strong>⚠️ 注意:</strong>此功能并非绝对安全!</p>
<ul style="padding-left: 20px; margin-top: 4px; font-size: 0.9rem;">
<li>同一浏览器中,密文只能解密一次</li>
<li>清除浏览器数据可重置</li>
<li>适用于非对抗环境</li>
</ul>
</div>
<div class="row" style="margin-top: 12px;">
<button id="clearRecordsBtn" class="secondary" style="width: auto; padding: 8px 12px;">清除记录</button>
</div>
</div>
</div>
</div>
</section>
<section class="section">
<h2 class="section-title">
<svg viewBox="0 0 24 24"><path d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
输入文本与口令
</h2>
<div class="grid">
<div class="card">
<label for="plaintext">要加密的文本</label>
<textarea id="plaintext" rows="6" placeholder="在此输入要加密的文本..."></textarea>
<div class="row">
<button id="clearTextBtn" class="secondary">清空</button>
<button id="sampleTextBtn" class="secondary">示例文本</button>
</div>
</div>
<div class="card">
<label for="password">口令</label>
<div class="password-group">
<input id="password" type="password" placeholder="输入加密口令...">
<button id="togglePassword" class="toggle-password" title="显示/隐藏口令">👁️</button>
</div>
<div class="strength-meter"><div id="strengthBar" class="strength-bar"></div></div>
<div id="strengthText" class="strength-text">口令强度</div>
<div class="row" style="margin-top: 16px;">
<button id="genBtn" class="secondary">生成口令</button>
<button id="copyPassBtn" class="secondary">复制口令</button>
</div>
</div>
</div>
</section>
<section class="section">
<h2 class="section-title">
<svg viewBox="0 0 24 24"><path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
操作
</h2>
<div class="action-buttons">
<button id="encryptBtn">加密文本</button>
<button id="decryptBtn" class="secondary">解密文本</button>
<button id="copyBtn" class="secondary">复制输出</button>
<button id="downloadBtn" class="secondary">下载密文</button>
<a href="verify.html" style="text-decoration: none;"><button class="secondary">文件校验</button></a>
</div>
</section>
<section class="section">
<h2 class="section-title">
<svg viewBox="0 0 24 24"><path d="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4"/></svg>
输出结果
</h2>
<div class="output-container">
<label for="output">加密输出(Base64 JSON格式)</label>
<textarea id="output" rows="6" placeholder="加密或解密的结果将显示在这里..."></textarea>
<div class="output-actions">
<button class="output-btn" id="formatOutputBtn">格式化</button>
<button class="output-btn" id="copyBtn2">复制</button>
</div>
</div>
<div class="row" style="margin-top: 12px;">
<button id="clearOutputBtn" class="secondary">清空输出</button>
<div id="operationStatus" class="status" style="flex: 1; display: none;"></div>
</div>
</section>
<div class="tips">
<h3>安全使用建议</h3>
<ul>
<li>🔒 离线使用时打包整套文件</li>
<li>⚠️ 一次性解密仅为"防君子"模式</li>
<li>🔑 口令至少12位,包含大小写字母、数字和特殊字符</li>
<li>📱 通过不同渠道传输密文和口令</li>
</ul>
</div>
</main>
<script>
// 配置
const CONFIG = {
PBKDF2_ITERATIONS: 200000,
DEFAULT_PRESET: 'MODERATE',
SALT_LENGTHS: { ARGON2: 16, PBKDF2: 16 },
ONE_TIME_STORAGE_KEY: 'cryptolock_one_time_ids'
};
// 工具函数
const utils = {
encoder: new TextEncoder(),
decoder: new TextDecoder(),
randomBytes(length) {
const bytes = new Uint8Array(length);
crypto.getRandomValues(bytes);
return bytes;
},
arrayBufferToBase64(buffer) {
const bytes = new Uint8Array(buffer);
return btoa(String.fromCharCode(...bytes));
},
base64ToArrayBuffer(base64) {
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
return bytes.buffer;
},
calculatePasswordStrength(password) {
if (!password) return { score: 0, text: '未输入' };
let score = 0;
const length = password.length;
if (length >= 8) score += 1;
if (length >= 12) score += 1;
if (length >= 16) score += 1;
if (/[a-z]/.test(password)) score += 1;
if (/[A-Z]/.test(password)) score += 1;
if (/[0-9]/.test(password)) score += 1;
if (/[^a-zA-Z0-9]/.test(password)) score += 1;
const percentage = Math.min(100, Math.round((score / 8) * 100));
let text, color;
if (percentage < 30) { text = '弱'; color = '#dc2626'; }
else if (percentage < 60) { text = '一般'; color = '#f59e0b'; }
else if (percentage < 80) { text = '良好'; color = '#16a34a'; }
else { text = '强'; color = '#059669'; }
return { score: percentage, text: `${text} (${percentage}%)`, color };
},
showStatus(message, type = 'info', duration = 3000) {
const statusEl = document.getElementById('operationStatus');
statusEl.innerHTML = message;
statusEl.className = `status ${type}`;
statusEl.style.display = 'flex';
if (duration > 0) setTimeout(() => statusEl.style.display = 'none', duration);
},
generateOneTimeId() {
return utils.arrayBufferToBase64(crypto.getRandomValues(new Uint8Array(16)));
},
getDecryptedIds() {
try {
const stored = localStorage.getItem(CONFIG.ONE_TIME_STORAGE_KEY);
return stored ? JSON.parse(stored) : [];
} catch { return []; }
},
addDecryptedId(id) {
const ids = utils.getDecryptedIds();
if (!ids.includes(id)) {
ids.push(id);
localStorage.setItem(CONFIG.ONE_TIME_STORAGE_KEY, JSON.stringify(ids));
}
},
isIdDecrypted(id) {
return utils.getDecryptedIds().includes(id);
},
clearDecryptedIds() {
localStorage.removeItem(CONFIG.ONE_TIME_STORAGE_KEY);
}
};
// 核心变量
let sodiumReady = false;
let sodium = null;
// 更新KDF状态
function updateKdfStatus() {
const statusEl = document.getElementById('kdfStatus');
if (sodiumReady) {
statusEl.innerHTML = '<strong>✅ Argon2id 可用</strong>';
statusEl.className = 'status ok';
} else {
statusEl.innerHTML = '<strong>⚠️ 使用 PBKDF2 回退</strong>';
statusEl.className = 'status warning';
}
}
// 检测sodium
async function detectSodium() {
if (window.sodium) {
sodium = window.sodium;
try {
await sodium.ready;
sodiumReady = true;
} catch { sodiumReady = false; }
}
updateKdfStatus();
}
// 密钥派生
async function deriveKey(password, salt, preset = CONFIG.DEFAULT_PRESET) {
if (sodiumReady) {
let opsLimit, memLimit;
if (preset === 'INTERACTIVE') {
opsLimit = sodium.crypto_pwhash_OPSLIMIT_INTERACTIVE;
memLimit = sodium.crypto_pwhash_MEMLIMIT_INTERACTIVE;
} else if (preset === 'SENSITIVE') {
opsLimit = sodium.crypto_pwhash_OPSLIMIT_SENSITIVE;
memLimit = sodium.crypto_pwhash_MEMLIMIT_SENSITIVE;
} else {
opsLimit = sodium.crypto_pwhash_OPSLIMIT_MODERATE;
memLimit = sodium.crypto_pwhash_MEMLIMIT_MODERATE;
}
const saltBytes = salt instanceof Uint8Array ? salt : new Uint8Array(salt);
const keyBytes = sodium.crypto_pwhash(32, password, saltBytes, opsLimit, memLimit, sodium.crypto_pwhash_ALG_ARGON2ID13);
return crypto.subtle.importKey('raw', sodium.to_array_buffer(keyBytes),
{ name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
} else {
const passwordKey = await crypto.subtle.importKey('raw', utils.encoder.encode(password),
{ name: 'PBKDF2' }, false, ['deriveKey']);
return crypto.subtle.deriveKey(
{ name: 'PBKDF2', salt: salt.buffer || salt, iterations: CONFIG.PBKDF2_ITERATIONS, hash: 'SHA-256' },
passwordKey, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
}
}
// 加密
async function encryptText(plaintext, password) {
const startTime = performance.now();
const useOneTime = document.getElementById('enableOneTime').checked;
const oneTimeId = useOneTime ? utils.generateOneTimeId() : null;
const saltLength = sodiumReady ? CONFIG.SALT_LENGTHS.ARGON2 : CONFIG.SALT_LENGTHS.PBKDF2;
const salt = utils.randomBytes(saltLength);
const iv = utils.randomBytes(12);
const preset = document.getElementById('argonPreset').value;
const key = await deriveKey(password, salt, preset);
const ciphertext = await crypto.subtle.encrypt({ name: 'AES-GCM', iv: iv }, key, utils.encoder.encode(plaintext));
const payload = {
version: 2, timestamp: new Date().toISOString(), algorithm: 'AES-GCM-256',
kdf: sodiumReady ? 'argon2id' : 'pbkdf2', preset: sodiumReady ? preset : undefined,
salt: utils.arrayBufferToBase64(salt), iv: utils.arrayBufferToBase64(iv),
ciphertext: utils.arrayBufferToBase64(ciphertext), oneTimeId: oneTimeId
};
return {
payload: btoa(JSON.stringify(payload)),
duration: performance.now() - startTime,
usedOneTime: !!oneTimeId
};
}
// 解密
async function decryptText(encryptedData, password) {
const startTime = performance.now();
let payload;
try { payload = JSON.parse(atob(encryptedData)); } catch { throw new Error('密文格式错误'); }
if (!payload.salt || !payload.iv || !payload.ciphertext) throw new Error('密文缺少必要字段');
if (payload.oneTimeId && utils.isIdDecrypted(payload.oneTimeId)) throw new Error('此密文已被解密过');
const salt = new Uint8Array(utils.base64ToArrayBuffer(payload.salt));
const iv = new Uint8Array(utils.base64ToArrayBuffer(payload.iv));
const ciphertext = utils.base64ToArrayBuffer(payload.ciphertext);
const preset = payload.preset || document.getElementById('argonPreset').value;
const key = await deriveKey(password, salt, preset);
const plaintextBuffer = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: iv }, key, ciphertext);
if (payload.oneTimeId) utils.addDecryptedId(payload.oneTimeId);
return {
text: utils.decoder.decode(plaintextBuffer),
duration: performance.now() - startTime,
usedOneTime: !!payload.oneTimeId
};
}
// 事件监听器
function setupEventListeners() {
// 加密按钮
document.getElementById('encryptBtn').addEventListener('click', async () => {
const plaintext = document.getElementById('plaintext').value.trim();
const password = document.getElementById('password').value.trim();
if (!plaintext) return utils.showStatus('请输入要加密的文本', 'warning');
if (!password) return utils.showStatus('请输入加密口令', 'warning');
const btn = document.getElementById('encryptBtn');
btn.disabled = true;
btn.innerHTML = '<span class="loading"></span> 加密中...';
try {
const { payload, duration, usedOneTime } = await encryptText(plaintext, password);
document.getElementById('output').value = payload;
utils.showStatus(`✅ 加密完成 (${duration.toFixed(0)}ms)` + (usedOneTime ? ',已启用一次性解密' : ''), 'ok');
} catch (error) {
console.error('加密失败:', error);
utils.showStatus(`加密失败: ${error.message}`, 'error');
} finally {
btn.disabled = false;
btn.innerHTML = '加密文本';
}
});
// 解密按钮
document.getElementById('decryptBtn').addEventListener('click', async () => {
const encryptedData = document.getElementById('output').value.trim();
const password = document.getElementById('password').value.trim();
if (!encryptedData) return utils.showStatus('请输入要解密的密文', 'warning');
if (!password) return utils.showStatus('请输入解密口令', 'warning');
const btn = document.getElementById('decryptBtn');
btn.disabled = true;
btn.innerHTML = '<span class="loading"></span> 解密中...';
try {
const { text, duration, usedOneTime } = await decryptText(encryptedData, password);
document.getElementById('plaintext').value = text;
utils.showStatus(`✅ 解密完成 (${duration.toFixed(0)}ms)` + (usedOneTime ? ',已标记为已解密' : ''), 'ok');
} catch (error) {
console.error('解密失败:', error);
utils.showStatus(`解密失败: ${error.message}`, 'error');
} finally {
btn.disabled = false;
btn.innerHTML = '解密文本';
}
});
// 其他按钮
document.getElementById('genBtn').addEventListener('click', () => {
const charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*';
const randomValues = new Uint8Array(20);
crypto.getRandomValues(randomValues);
let password = '';
for (let i = 0; i < 20; i++) password += charset[randomValues[i] % charset.length];
document.getElementById('password').value = password;
updatePasswordStrength();
utils.showStatus('✅ 已生成随机口令', 'ok');
});
document.getElementById('copyPassBtn').addEventListener('click', async () => {
const password = document.getElementById('password').value;
if (!password) return utils.showStatus('没有口令可复制', 'warning');
try {
await navigator.clipboard.writeText(password);
utils.showStatus('✅ 口令已复制', 'ok');
} catch { utils.showStatus('复制失败', 'error'); }
});
document.getElementById('copyBtn').addEventListener('click', async () => {
const output = document.getElementById('output').value;
if (!output) return utils.showStatus('没有输出可复制', 'warning');
try {
await navigator.clipboard.writeText(output);
utils.showStatus('✅ 输出已复制', 'ok');
} catch { utils.showStatus('复制失败', 'error'); }
});
document.getElementById('copyBtn2').addEventListener('click', async () => {
const output = document.getElementById('output').value;
if (!output) return utils.showStatus('没有输出可复制', 'warning');
try {
await navigator.clipboard.writeText(output);
utils.showStatus('✅ 输出已复制', 'ok');
} catch { utils.showStatus('复制失败', 'error'); }
});
document.getElementById('downloadBtn').addEventListener('click', () => {
const output = document.getElementById('output').value;
if (!output) return utils.showStatus('没有输出可下载', 'warning');
const blob = new Blob([output], { type: 'text/plain;charset=utf-8' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `encrypted_${Date.now()}.txt`;
a.click();
URL.revokeObjectURL(url);
utils.showStatus('✅ 输出已下载', 'ok');
});
document.getElementById('clearTextBtn').addEventListener('click', () => {
document.getElementById('plaintext').value = '';
utils.showStatus('已清空输入文本', 'info');
});
document.getElementById('clearOutputBtn').addEventListener('click', () => {
document.getElementById('output').value = '';
utils.showStatus('已清空输出', 'info');
});
document.getElementById('sampleTextBtn').addEventListener('click', () => {
document.getElementById('plaintext').value = `这是一个加密示例文本。\n\n使用说明:\n1. 输入强口令\n2. 点击"加密文本"\n3. 发送密文\n4. 通过另一渠道告知口令`;
utils.showStatus('已加载示例文本', 'info');
});
document.getElementById('togglePassword').addEventListener('click', () => {
const passInput = document.getElementById('password');
passInput.type = passInput.type === 'password' ? 'text' : 'password';
});
document.getElementById('formatOutputBtn').addEventListener('click', () => {
const output = document.getElementById('output').value;
if (!output) return utils.showStatus('没有输出可格式化', 'warning');
try {
const parsed = JSON.parse(atob(output));
document.getElementById('output').value = btoa(JSON.stringify(parsed, null, 2));
utils.showStatus('✅ 输出已格式化', 'ok');
} catch { utils.showStatus('格式化失败', 'error'); }
});
document.getElementById('loadSodiumBtn').addEventListener('click', async () => {
const btn = document.getElementById('loadSodiumBtn');
btn.disabled = true;
btn.innerHTML = '<span class="loading"></span> 加载中...';
try {
const script = document.createElement('script');
script.src = 'https://cdn.jsdelivr.net/npm/libsodium-wrappers@0.7.10/dist/modules/libsodium-wrappers.min.js';
await new Promise((resolve, reject) => {
script.onload = resolve;
script.onerror = reject;
document.head.appendChild(script);
});
await sodium.ready;
sodiumReady = true;
updateKdfStatus();
utils.showStatus('✅ libsodium 已加载', 'ok');
} catch (error) {
console.error('加载libsodium失败:', error);
utils.showStatus('❌ 加载失败,使用PBKDF2', 'error');
} finally {
btn.disabled = false;
btn.textContent = '加载 libsodium';
}
});
document.getElementById('enableOneTime').addEventListener('change', function() {
document.getElementById('oneTimeSettings').style.display = this.checked ? 'block' : 'none';
const count = utils.getDecryptedIds().length;
if (count > 0) utils.showStatus(`已记录 ${count} 条解密记录`, 'info', 2000);
});
document.getElementById('clearRecordsBtn').addEventListener('click', () => {
utils.clearDecryptedIds();
utils.showStatus('✅ 解密记录已清除', 'ok');
});
document.getElementById('password').addEventListener('input', updatePasswordStrength);
// 键盘快捷键
document.addEventListener('keydown', (e) => {
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
if (document.getElementById('plaintext').value && document.getElementById('password').value) {
e.preventDefault();
document.getElementById('encryptBtn').click();
}
}
});
}
// 更新口令强度
function updatePasswordStrength() {
const password = document.getElementById('password').value;
const strength = utils.calculatePasswordStrength(password);
document.getElementById('strengthBar').style.width = `${strength.score}%`;
document.getElementById('strengthBar').style.backgroundColor = strength.color;
document.getElementById('strengthText').textContent = `口令强度: ${strength.text}`;
}
// 初始化
async function init() {
await detectSodium();
setupEventListeners();
updatePasswordStrength();
utils.showStatus('工具已准备就绪', 'ok', 2000);
}
document.addEventListener('DOMContentLoaded', init);
</script>
</body>
</html>