-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.js
578 lines (490 loc) · 13.7 KB
/
app.js
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
"use strict";
/**
MSPPS holds the GUI values for the message, seed, key, and signature.
Msg: Msg in bytes, UTF-8 if relevant.
SedHex: Seed Hex.
PubHex: Public Key Hex.
KypHex: (Key Pair) Seed || Public Key.
SigHex: Signature Hex.
Sed64: Seed b64.
Puk64: Public Key b64.
Kyp64: (Key Pair) Seed || Public Key.
Sig64: Signature b64.
Sedb: Seed bytes.
Pukb: Public Key
Kypb: (Key Pair) Seed || Public Key.
Sigb: Signature.
@typedef {object} MSPPS
@property {Uint8} Msg
@property {Hex} SedHex
@property {Hex} PukHex
@property {Hex} KypHex
@property {Hex} SigHex
@property {B64} Sed64
@property {B64} Puk64
@property {B64} Kyp64
@property {B64} Sig64
@property {Uint8} Sedb
@property {Uint8} Pukb
@property {Uint8} Kypb
@property {Uint8} Sigb
*/
const EmptyMSPPS = {
Msg: "",
SedHex: "",
PukHex: "",
KypHex: "",
SigHex: "",
Sed64: "",
Puk64: "",
Kyp64: "",
Sig64: "",
Sedb: "",
Pukb: "",
Kypb: "",
Sigb: "",
}
const AppMsgEmpty = "---"
// Variable for encoding change.
var CurrentKeyEnc
var InitedFormOptions
// GUI Element variables
var AlgType;
var InputMsg;
var MsgEnc;
var KeyEnc;
var Seed;
var PublicKey;
var Signature;
var Kyp;
var AppMessage;
// URLFormJS sticky form
/**@type {FormOptions} */
const FormOptions = {
"FormParameters": [{
"name": "alg_type",
"id": "AlgType",
}, {
"name": "msg_enc",
"id": "MsgEnc",
}, {
"name": "msg",
"id": "InputMsg",
}, {
"name": "key_enc",
"id": "KeyEnc",
}, {
"name": "seed",
"id": "Seed",
}, {
"name": "key",
"id": "PublicKey",
}, {
"name": "sig",
"id": "Signature",
},
// Non-GUI options
{
"name": "verify",
"type": "bool",
//"nonFormValue": true,
"funcTrue": async function() {
CurrentKeyEnc = KeyEnc.value;
Verify();
},
},
]
};
// DOM load
document.addEventListener('DOMContentLoaded', async () => {
// Grab GUI elements into variables.
AlgType = document.getElementById('AlgType');
InputMsg = document.getElementById('InputMsg');
MsgEnc = document.getElementById('MsgEnc');
KeyEnc = document.getElementById('KeyEnc');
Seed = document.getElementById('Seed');
PublicKey = document.getElementById('PublicKey');
Signature = document.getElementById('Signature');
Kyp = document.getElementById('Kyp');
AppMessage = document.getElementById('AppMessage');
// ShareURL is encapsulate in a try/catch so the dependency is not required for functionality.
try {
InitedFormOptions = await URLForm.Init(FormOptions)
await URLForm.Populate(InitedFormOptions);
} catch (e) {
console.info("Unable to start share button/share link (URLFormJS). If this was suppose to work, see the docs on cloning `URLFormJS`.");
document.querySelectorAll('.shareElement').forEach(function(e) {
e.style.display = 'none';
});
}
// Initialize
AppMessage.textContent = AppMsgEmpty;
CurrentKeyEnc = KeyEnc.value; // Ensure key current encoding matches GUI after ShareURL may have set it.
// Set event listeners for buttons.
document.getElementById('GenRandKeyPairBtn').addEventListener('click', GenRadomGUI);
document.getElementById('GenKeyFromSeedBtn').addEventListener('click', KeyFromSeedBtn);
document.getElementById('SignBtn').addEventListener('click', Sign);
document.getElementById('VerifyBtn').addEventListener('click', Verify);
document.getElementById('ClearBtn').addEventListener('click', ClearAll);
KeyEnc.addEventListener('change', ChangeKeyEncGui);
});
/**
GetMSPPS gets values from gui and returns MSPPS.
@returns {MSPPS}
*/
async function GetMSPPS() {
/** @type {MSPPS} */
let MSPPS = {};
let Msg = InputMsg.value;
switch (MsgEnc.value) {
case "B64":
MSPPS.Msg = new Uint8Array(await HexToUI8(B64ToHex(Msg)));
break;
case "Hex":
MSPPS.Msg = new Uint8Array(await HexToUI8(Msg));
break;
case "Text":
let enc = new TextEncoder("utf-8"); // Suppose to be always in UTF-8.
MSPPS.Msg = new Uint8Array(enc.encode(Msg));
break;
default:
console.error('unsupported message encoding');
return null;
}
if (AlgType.value === "Dig") {
// TODO, Support Ed25519ph
let err = "Ed25519ph is currently not supported.";
AppMessage.textContent = err;
throw new Error(err);
}
let Sed = Seed.value;
let Puk = PublicKey.value;
let Sig = Signature.value;
if (CurrentKeyEnc === "Hex") {
MSPPS.SedHex = Sed;
MSPPS.PukHex = Puk;
MSPPS.KypHex = Sed + Puk;
MSPPS.SigHex = Sig;
} else if (CurrentKeyEnc === "B64") {
MSPPS.SedHex = B64ToHex(Sed);
MSPPS.PukHex = B64ToHex(Puk);
MSPPS.KypHex = B64ToHex(Sed) + B64ToHex(Puk);
MSPPS.SigHex = B64ToHex(Sig);
}
if (!isEmpty(MSPPS.SedHex)) {
if (MSPPS.SedHex.length == 128) {
// Check if seed/private key is 64 bytes. If so, assume `seed || public key`
// and discard given public key.
MSPPS.SedHex = MSPPS.SedHex.slice(0, 64);
}
if (MSPPS.SedHex.length !== 64) {
throw new SyntaxError("Seed is not 32 bytes.")
}
}
try {
await SetMSPPSFromHex(MSPPS);
if (isEmpty(MSPPS.Pukb)) {
KeyFromSeed(MSPPS);
}
} catch (error) {
AppMessage.textContent = "❌ " + error;
return;
}
return MSPPS;
}
/**
SetMSPPSFromHex sets the byte and base64 values from the Hex values.
Sets in place.
@param {MSPPS} MSPPS
*/
async function SetMSPPSFromHex(MSPPS) {
//console.log(MSPPS);
MSPPS.Sed64 = await HexTob64ut(MSPPS.SedHex);
MSPPS.Puk64 = await HexTob64ut(MSPPS.PukHex);
MSPPS.Sig64 = await HexTob64ut(MSPPS.SigHex);
MSPPS.Kyp64 = await HexTob64ut(MSPPS.KypHex);
MSPPS.Sedb = await HexToUI8(MSPPS.SedHex);
MSPPS.Pukb = await HexToUI8(MSPPS.PukHex);
MSPPS.Sigb = await HexToUI8(MSPPS.SigHex);
MSPPS.Kypb = await HexToUI8(MSPPS.KypHex);
}
// Change key values, seed, public key, sig, and KeyPair, to Hex or B64 encoding
// depending on Key Encoding.
async function ChangeKeyEncGui() {
console.log("ChangeKeyEncGui", CurrentKeyEnc, KeyEnc.value)
let MSPPS = await GetMSPPS();
await SetGuiIn(MSPPS);
CurrentKeyEnc = KeyEnc.value
}
/**
SetGuiIn sets the input GUI.
@param {MSPPS} MSPPS
*/
async function SetGuiIn(MSPPS) {
console.log(MSPPS);
if (KeyEnc.value === "Hex") {
Seed.value = MSPPS.SedHex;
PublicKey.value = MSPPS.PukHex;
Signature.value = MSPPS.SigHex;
Kyp.textContent = MSPPS.KypHex;
}
if (KeyEnc.value === "B64") {
Seed.value = MSPPS.Sed64;
PublicKey.value = MSPPS.Puk64;
Signature.value = MSPPS.Sig64;
Kyp.textContent = MSPPS.Kyp64;
}
}
/**
GenRadomGUI generates a random seed, private key, and public key.
@returns {void}
*/
async function GenRadomGUI() {
AppMessage.textContent = AppMsgEmpty;
let MSPPS = {};
MSPPS.Sedb = await crypto.getRandomValues(new Uint8Array(32));
//await HexToUI8()
MSPPS.SedHex = await ArrayBufferToHex(MSPPS.Sedb);
let k = await window.nobleEd25519.utils.getExtendedPublicKey(MSPPS.Sedb);
MSPPS.PukHex = k.point.toHex().toUpperCase();
MSPPS.KypHex = MSPPS.SedHex + MSPPS.PukHex;
MSPPS.SigHex = "";
await SetMSPPSFromHex(MSPPS);
await SetGuiIn(MSPPS);
}
/**
KeyFromSeed gets generates public key from MSPPS.Sedb.
*/
async function KeyFromSeed(MSPPS) {
console.log("KeyFromSeed", MSPPS);
// Ed25519 uses the lower 32 bytes of SHA-512
// https://datatracker.ietf.org/doc/html/rfc8032#section-5.1.5
let k = await window.nobleEd25519.utils.getExtendedPublicKey(MSPPS.Sedb);
MSPPS.PukHex = k.point.toHex().toUpperCase();
MSPPS.KypHex = MSPPS.SedHex + MSPPS.PukHex;
MSPPS.Puk64 = await HexTob64ut(MSPPS.PukHex);
MSPPS.Kyp64 = await HexTob64ut(MSPPS.KypHex);
}
async function KeyFromSeedBtn() {
try {
AppMessage.textContent = AppMsgEmpty;
let MSPPS = await GetMSPPS();
await KeyFromSeed(MSPPS)
SetGuiIn(MSPPS);
} catch (error) {
AppMessage.textContent = "❌ " + error;
return;
}
}
/**
Sign signs the current input message, depending on selected encoding method.
@returns {void}
*/
async function Sign() {
AppMessage.textContent = AppMsgEmpty;
try {
Signature.value = "";
var MSPPS = await GetMSPPS();
if (MSPPS.Sedb === undefined) {
throw new SyntaxError("Private key is empty.")
}
MSPPS.SigHex = await ArrayBufferToHex(await window.nobleEd25519.sign(MSPPS.Msg, MSPPS.Sedb));
if (MSPPS.SigHex.length !== 128) { // Sanity check
throw new RangeError("Invalid Signature length")
}
} catch (error) {
AppMessage.textContent = "❌ " + error;
return;
}
MSPPS.Sig64 = await HexTob64ut(MSPPS.SigHex);
await SetGuiIn(MSPPS);
Verify();
}
/**
Verify verifies the current signature with the current message and public
key. Populates "#AppMessage" fail/success/error messages.
@returns {void}
*/
async function Verify() {
AppMessage.textContent = AppMsgEmpty;
try {
let MSPPS = await GetMSPPS();
console.log("Verify", MSPPS)
var valid = await window.nobleEd25519.verify(MSPPS.Sigb, MSPPS.Msg, MSPPS.Pukb);
} catch (error) {
console.error(error);
}
if (!valid) {
AppMessage.textContent = "❌ Invalid Signature";
return;
}
AppMessage.textContent = "✅ Valid Signature";
}
/**
ClearAll clears all GUI fields.
@returns {void}
*/
async function ClearAll() {
InputMsg.value = "";
Seed.value = "";
PublicKey.value = "";
Signature.value = "";
AppMessage.textContent = AppMsgEmpty;
URLForm.Clear(InitedFormOptions)
SetGuiIn(EmptyMSPPS);
}
////////////////////////////////
// Taken from Cyphrme Lib
////////////////////////////////
/**
B64ToHex takes any RFC 4648 base64 to Hex.
@param {string} b64 RFC 4648 any base64.
@returns {string} Hex representation.
*/
function B64ToHex(b64) {
let ub64 = URISafeToUnsafe(b64);
const raw = atob(ub64);
let result = '';
for (let i = 0; i < raw.length; i++) {
const hex = raw.charCodeAt(i).toString(16).toUpperCase();
result += (hex.length === 2 ? hex : '0' + hex);
}
return result;
};
/**
URISafeToUnsafe converts any URI safe string to URI unsafe.
@param {string} b64ut
@returns {string} ub64t
*/
function URISafeToUnsafe(ub64) {
return ub64.replace(/-/g, '+').replace(/_/g, '/');
};
/**
HexTob64ut is hex to "RFC 4648 URI Safe Truncated".
@param {string} hex Hex representation.
@returns {string} b64ut RFC 4648 URI safe truncated.
*/
async function HexTob64ut(hex) {
let ab = await HexToUI8(hex);
return await ArrayBufferTo64ut(ab);
};
/**
URIUnsafeToSafe converts any URI unsafe string to URI safe.
@param {string} ub64t
@returns {string} b64ut
*/
function URIUnsafeToSafe(ub64) {
return ub64.replace(/\+/g, '-').replace(/\//g, '_');
};
/**
base64t removes base64 padding if applicable.
@param {string} base64
@returns {string} base64t
*/
function base64t(base64) {
return base64.replace(/=/g, '');
}
/**
ArrayBufferTo64ut Array buffer to b64ut.
@param {ArrayBuffer} buffer
@returns {string} base64ut.
*/
function ArrayBufferTo64ut(buffer) {
var string = String.fromCharCode.apply(null, new Uint8Array(buffer));
return base64t(URIUnsafeToSafe(btoa(string)));
};
/**
HexToUI8 converts string Hex to UInt8Array.
@param {Hex} Hex String Hex.
@returns {Uint8Array} ArrayBuffer.
*/
async function HexToUI8(hex) {
if (hex === undefined) { // undefined is different from 0 since 0 == "AA"
return new Uint8Array();
}
if ((hex.length % 2) !== 0) {
throw new RangeError('HexToUI8: Hex is not even.')
}
var a = new Uint8Array(hex.length / 2)
for (var i = 0; i < hex.length; i += 2) {
a[i / 2] = parseInt(hex.substring(i, i + 2), 16)
}
return a;
};
/**
ArrayBufferToHex accepts an array buffer and returns a string of hex.
Taken from https://stackoverflow.com/a/50767210/1923095
@param {ArrayBuffer} buffer Buffer that is being converted to UTF8
@returns {string} String with hex.
*/
async function ArrayBufferToHex(buffer) {
return [...new Uint8Array(buffer)].map(x => x.toString(16).padStart(2, "0")).join('').toUpperCase();
// Alternatively:
// let hashArray = Array.from(new Uint8Array(digest)); // convert buffer to byte array
// let hexHash = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
};
///////////////////////////////////
// Helpers - Taken from Cyphr.me
///////////////////////////////////
/**
isEmpty is a helper function to determine if thing is empty.
Functions are considered always not empty.
Arrays: Only if an array has no elements it is empty. isEmpty does not check
element contents. (For item contents, do: `isEmpty(array[0])`)
Objects are empty if they have no keys. (Returns len === 0 of object keys.)
NaN returns true. (NaN === NaN is always false, as NaN is never equal to
anything. NaN is the only JavaScript value unequal to itself.)
Don't use on HTMl elements. For HTML elements, use the !== equality check
(element !== null). TODO fix this
Cannot use CryptoKey with this function since (len === 0) always.
@param {any} thing Thing you wish was empty.
@returns {boolean} Boolean.
*/
function isEmpty(thing) {
if (typeof thing === 'function') {
return false
}
if (Array.isArray(thing)) {
if(thing.length == 0){
return true
}
}
if (thing === Object(thing)) {
if (Object.keys(thing).length === 0) {
return true
}
return false
}
if (!isBool(thing)) {
return true
}
return false
}
/**
Helper function to determine boolean.
Javascript, instead of considering everything false except a few key words,
decided everything is true instead of a few key words. Why? Because
Javascript. This function inverts that assumption, so that everything can be
considered false unless true.
@param {any} bool Thing that you wish was a boolean.
@returns {boolean} An actual boolean.
*/
function isBool(bool) {
if (
bool === false ||
bool === "false" ||
bool === undefined ||
bool === "undefined" ||
bool === "" ||
bool === 0 ||
bool === "0" ||
bool === null ||
bool === "null" ||
bool === "NaN" ||
Number.isNaN(bool) ||
bool === Object(bool) // isObject
) {
return false
}
return true
}