-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
262 lines (241 loc) · 13.9 KB
/
index.html
File metadata and controls
262 lines (241 loc) · 13.9 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
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>ECIES P‑256 — короткие ключи (WebCrypto, офлайн)</title>
<style>
:root{--bg:#0f1220;--panel:#171b2e;--muted:#8fa1c1;--text:#e7ecf7;--brand:#6aa3ff;--accent:#9effc3;--danger:#ff6a6a;--radius:16px}
*{box-sizing:border-box} body{margin:0;font-family:Inter,ui-sans-serif,system-ui,Segoe UI,Roboto,Arial; background:linear-gradient(180deg,#0b0e1a,#12172a 40%,#0f1220); color:var(--text)}
.wrap{max-width:1100px;margin:24px auto;padding:20px}
h1{margin:0 0 8px;font-size:28px} .lead{color:var(--muted);margin:0 0 16px}
.grid{display:grid;grid-template-columns:1fr;gap:16px} @media(min-width:980px){.grid{grid-template-columns:1fr 1fr}}
.card{background:var(--panel);border:1px solid rgba(255,255,255,.06);border-radius:var(--radius);padding:16px;box-shadow:0 10px 30px rgba(0,0,0,.25)}
.card h2{margin:0 0 12px;font-size:18px}
label{display:block;font-size:12px;color:var(--muted);margin:12px 0 6px}
textarea,input{width:100%;background:#0e1224;color:var(--text);border:1px solid rgba(255,255,255,.08);border-radius:12px;padding:10px 12px;font:inherit}
textarea{min-height:96px;resize:vertical} textarea.small{min-height:64px}
.row{display:flex;gap:8px;flex-wrap:wrap;align-items:center}
button{appearance:none;border:0;background:linear-gradient(180deg,#2a72ff,#1f56c9);color:#fff;padding:10px 14px;border-radius:12px;font-weight:600;cursor:pointer}
button.secondary{background:#212843;color:var(--text);border:1px solid rgba(255,255,255,.08)}
button.ghost{background:transparent;color:var(--muted)}
select{background:#0e1224;color:var(--text);border:1px solid rgba(255,255,255,.08);border-radius:10px;padding:8px 10px}
.mono{font-family:ui-monospace,Menlo,Consolas,monospace;font-size:12px}
.hint{font-size:12px;color:var(--muted)} .ok{color:var(--accent)} .err{color:var(--danger)}
</style>
</head>
<body>
<div class="wrap">
<h1>ECIES P‑256 — шифрование с ультра‑коротким публичным ключом</h1>
<p class="lead">Всё офлайн в браузере (WebCrypto). Публичный ключ формата RAW (base64url) — <b>~88 символов</b>, подходит под лимит 250.</p>
<div class="grid">
<section class="card">
<h2>1) Мои ключи (ECDH P‑256)</h2>
<div class="row">
<button id="btnGen">Сгенерировать</button>
<button id="btnClearKeys" class="secondary">Очистить</button>
</div>
<label>Публичный ключ (выбери формат для чатов)</label>
<div class="row">
<select id="pubFmt">
<option value="raw">RAW (base64url, 88 симв.) — самый короткий</option>
<option value="jwk">JWK (minified JSON)</option>
<option value="pem" selected>PEM (SPKI)</option>
</select>
<button id="btnCopyPub" class="secondary">Скопировать</button>
</div>
<textarea id="pubOut" class="mono small" placeholder="Публичный ключ…"></textarea>
<label>Приватный ключ (PKCS#8 PEM)</label>
<div class="row">
<button id="btnCopyPriv" class="secondary">Скопировать</button>
<button id="btnImportPriv" class="secondary">Импортировать из PEM</button>
</div>
<textarea id="privPem" class="mono" placeholder="-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----"></textarea>
<div id="keysStatus" class="hint">Статус: ключи не загружены</div>
</section>
<section class="card">
<h2>2) Шифрование чужим ключом</h2>
<label>Чужой публичный ключ</label>
<div class="row">
<select id="foreignFmt">
<option value="raw">RAW (base64url)</option>
<option value="jwk">JWK</option>
<option value="pem" selected>PEM</option>
</select>
<button id="btnImportForeign" class="secondary">Импортировать</button>
</div>
<textarea id="foreignKeyIn" class="mono small" placeholder="Вставь чужой публичный ключ выбранного формата"></textarea>
<label>Сообщение</label>
<textarea id="plainText" placeholder="Текст, который сможет прочитать только владелец приватного ключа"></textarea>
<div class="row">
<button id="btnEncrypt">Зашифровать (ECIES P‑256 + AES‑GCM)</button>
</div>
<label>Шифропакет (минимальный JSON или его Base64)</label>
<div class="row">
<select id="packFmt">
<option value="json" selected>JSON компактный</option>
<option value="b64">Base64(JSON)</option>
</select>
<button id="btnCopyPack" class="secondary">Скопировать</button>
</div>
<textarea id="cipherOut" class="mono"></textarea>
<div id="encStatus" class="hint"></div>
</section>
<section class="card">
<h2>3) Расшифровка моим приватным</h2>
<label>Вставь шифропакет (JSON или Base64 от JSON)</label>
<textarea id="cipherIn" class="mono"></textarea>
<div class="row">
<button id="btnDecrypt">Расшифровать</button>
</div>
<label>Расшифрованный текст</label>
<textarea id="plainOut" class="small"></textarea>
<div id="decStatus" class="hint"></div>
</section>
<section class="card">
<h2>Справка</h2>
<ul class="hint">
<li>Алгоритм: ECIES (ECDH P‑256 → AES‑GCM‑256). Эфемерный ключ в пакете.</li>
<li>Форматы публичного ключа: <b>RAW</b> (base64url 88 симв.), <b>JWK</b>, <b>PEM</b>.</li>
<li>Пакет JSON минимален: <code>{"s":"P256","e":"...","i":"...","c":"..."}</code> (схема, эфемерный ключ RAW, IV, шифртекст).</li>
<li>Всё локально, ничего не отправляется в сеть.</li>
</ul>
</section>
</div>
</div>
<script>
const enc = new TextEncoder();
const dec = new TextDecoder();
const $ = id => document.getElementById(id);
let myPublicKey = null; // CryptoKey (ECDH P-256)
let myPrivateKey = null; // CryptoKey
let foreignPublicKey = null; // CryptoKey
let lastPkg = null; // ECIES package
// ===== utilities =====
function b64u(buf){ // base64url from ArrayBuffer
let s = btoa(String.fromCharCode(...new Uint8Array(buf)));
return s.replace(/\+/g,'-').replace(/\//g,'_').replace(/=+$/,'');
}
function ub64u(s){ // ArrayBuffer from base64url
s = s.replace(/-/g,'+').replace(/_/g,'/');
const pad = s.length % 4 ? 4 - (s.length % 4) : 0; s += '='.repeat(pad);
const bin = atob(s); const u8 = new Uint8Array(bin.length);
for(let i=0;i<bin.length;i++) u8[i]=bin.charCodeAt(i);
return u8.buffer;
}
function toPem(base64,label){ const chunk=base64.match(/.{1,64}/g)?.join('\n')||base64; return `-----BEGIN ${label}-----\n${chunk}\n-----END ${label}-----`; }
function fromPem(pem){ return pem.replace(/-----BEGIN [^-]+-----/g,'').replace(/-----END [^-]+-----/g,'').replace(/\s+/g,'').trim(); }
async function copyVal(id){ try{ await navigator.clipboard.writeText($(id).value); status($(id),'Скопировано',true);}catch{status($(id),'Не скопировано',false)} }
function status(el,msg,ok){ const d=document.createElement('div'); d.textContent=msg; d.className='hint '+(ok?'ok':'err'); el.after(d); setTimeout(()=>d.remove(),2000); }
// ===== key ops =====
async function gen(){
const kp = await crypto.subtle.generateKey({name:'ECDH', namedCurve:'P-256'}, true, ['deriveKey','deriveBits']);
myPublicKey = kp.publicKey; myPrivateKey = kp.privateKey; foreignPublicKey=null;
$('keysStatus').textContent='Ключи P‑256 сгенерированы.'; $('keysStatus').className='hint ok';
await showPub();
await showPriv();
}
async function showPub(){
if(!myPublicKey) await gen();
const fmt = $('pubFmt').value;
if(fmt==='raw'){
const raw = await crypto.subtle.exportKey('raw', myPublicKey); // 65 bytes (04||x||y)
$('pubOut').value = b64u(raw); // 88 символов
} else if(fmt==='jwk'){
const jwk = await crypto.subtle.exportKey('jwk', myPublicKey);
$('pubOut').value = JSON.stringify({kty:jwk.kty,crv:jwk.crv,x:jwk.x,y:jwk.y});
} else { // pem
const spki = await crypto.subtle.exportKey('spki', myPublicKey);
$('pubOut').value = toPem(btoa(String.fromCharCode(...new Uint8Array(spki))),'PUBLIC KEY');
}
}
async function showPriv(){
if(!myPrivateKey) await gen();
const pkcs8 = await crypto.subtle.exportKey('pkcs8', myPrivateKey);
$('privPem').value = toPem(btoa(String.fromCharCode(...new Uint8Array(pkcs8))),'PRIVATE KEY');
}
async function importPriv(){
try{
const buf = ub64u(fromPem($('privPem').value));
myPrivateKey = await crypto.subtle.importKey('pkcs8', buf, {name:'ECDH', namedCurve:'P-256'}, true, ['deriveKey','deriveBits']);
$('keysStatus').textContent='Приватный импортирован.'; $('keysStatus').className='hint ok';
}catch(e){ $('keysStatus').textContent='Ошибка импорта приватного: '+e.message; $('keysStatus').className='hint err'; }
}
async function importForeign(){
try{
const fmt = $('foreignFmt').value; const txt = $('foreignKeyIn').value.trim();
if(fmt==='raw'){
const raw = ub64u(txt);
foreignPublicKey = await crypto.subtle.importKey('raw', raw, {name:'ECDH', namedCurve:'P-256'}, true, []);
} else if(fmt==='jwk'){
const jwk = JSON.parse(txt);
foreignPublicKey = await crypto.subtle.importKey('jwk', jwk, {name:'ECDH', namedCurve:'P-256'}, true, []);
} else { // pem
const spki = ub64u(fromPem(txt));
foreignPublicKey = await crypto.subtle.importKey('spki', spki, {name:'ECDH', namedCurve:'P-256'}, true, []);
}
$('encStatus').textContent='Импортирован чужой публичный.'; $('encStatus').className='hint ok';
}catch(e){ $('encStatus').textContent='Ошибка импорта чужого ключа: '+e.message; $('encStatus').className='hint err'; }
}
// ===== ECIES (ECDH→AES‑GCM) =====
async function eciesEncrypt(recipientPubKey, msgU8){
const eph = await crypto.subtle.generateKey({name:'ECDH', namedCurve:'P-256'}, true, ['deriveKey']);
const aesKey = await crypto.subtle.deriveKey({name:'ECDH', public:recipientPubKey}, eph.privateKey, {name:'AES-GCM',length:256}, true, ['encrypt','decrypt']);
const iv = crypto.getRandomValues(new Uint8Array(12));
const ct = await crypto.subtle.encrypt({name:'AES-GCM', iv}, aesKey, msgU8);
const epkRaw = await crypto.subtle.exportKey('raw', eph.publicKey); // 65 bytes
return {s:'P256', e:b64u(epkRaw), i:b64u(iv), c:b64u(ct)}; // minimal keys
}
async function eciesDecrypt(pkg){
const epk = await crypto.subtle.importKey('raw', ub64u(pkg.e), {name:'ECDH', namedCurve:'P-256'}, true, []);
const aesKey = await crypto.subtle.deriveKey({name:'ECDH', public:epk}, myPrivateKey, {name:'AES-GCM',length:256}, false, ['decrypt']);
const iv = new Uint8Array(ub64u(pkg.i));
const pt = await crypto.subtle.decrypt({name:'AES-GCM', iv}, aesKey, ub64u(pkg.c));
return new Uint8Array(pt);
}
// ===== flows =====
async function doEncrypt(){
try{
if(!foreignPublicKey) await importForeign();
if(!foreignPublicKey) throw new Error('Нет публичного ключа адресата');
const pkg = await eciesEncrypt(foreignPublicKey, enc.encode($('plainText').value));
lastPkg = pkg;
makePack();
$('encStatus').textContent = 'Зашифровано.';
$('encStatus').className = 'hint ok';
}catch(e){ $('encStatus').textContent='Ошибка: '+e.message; $('encStatus').className='hint err'; }
}
function makePack(){
if(!lastPkg){ $('encStatus').textContent='Сначала зашифруйте сообщение.'; $('encStatus').className='hint err'; return; }
const fmt = $('packFmt').value; const json = JSON.stringify(lastPkg);
$('cipherOut').value = (fmt==='json') ? json : b64u(new TextEncoder().encode(json));
}
async function doDecrypt(){
try{
if(!myPrivateKey) await importPriv();
let raw = $('cipherIn').value.trim();
if(!raw){ $('decStatus').textContent='Пустой ввод.'; $('decStatus').className='hint err'; return; }
if(raw[0] !== '{'){ // вероятно Base64(JSON)
raw = dec.decode(ub64u(raw));
}
const pkg = JSON.parse(raw);
const textU8 = await eciesDecrypt(pkg);
$('plainOut').value = dec.decode(textU8);
$('decStatus').textContent='Расшифровано.'; $('decStatus').className='hint ok';
}catch(e){ $('decStatus').textContent='Ошибка: '+e.message; $('decStatus').className='hint err'; }
}
// ===== bindings =====
$('btnGen').addEventListener('click', gen);
$('btnClearKeys').addEventListener('click', ()=>{ myPublicKey=myPrivateKey=foreignPublicKey=null; $('pubOut').value=''; $('privPem').value=''; $('keysStatus').textContent='Статус: ключи не загружены'; $('keysStatus').className='hint'; });
$('pubFmt').addEventListener('change', showPub);
$('btnCopyPub').addEventListener('click', ()=>copyVal('pubOut'));
$('btnCopyPriv').addEventListener('click', ()=>copyVal('privPem'));
$('btnImportPriv').addEventListener('click', importPriv);
$('btnImportForeign').addEventListener('click', importForeign);
$('btnEncrypt').addEventListener('click', doEncrypt);
$('packFmt').addEventListener('change', makePack);
$('btnCopyPack').addEventListener('click', ()=>copyVal('cipherOut'));
$('btnDecrypt').addEventListener('click', doDecrypt);
</script>
</body>
</html>