-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
1221 lines (977 loc) · 35.5 KB
/
index.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
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
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ////////////////////////////////////////////////////////////////////////////
// ////////////////////////////////////////////////////////////////////////////
// ////////////////////////////////////////////////////////////////////////////
//
// Class with methods to make working with subtle crypto
// easier and more obvious
//
export default class EZCrypto {
constructor() {
this._crypto = undefined;
if(typeof window == "undefined" && typeof self == "undefined"){
this._nodeEnvLoad();
} else {
try{
this._crypto = window?.crypto;
this._crypto.CryptoKey = window?.CryptoKey;
} catch(e){
this._crypto = self?.crypto;
this._crypto.CryptoKey = self?.CryptoKey;
}
}
}
// //////////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////////
_nodeEnvLoad = async () => {
this._crypto = await Object.getPrototypeOf(async function(){}).constructor(
`
return await import( "crypto" ).then((m) => {return m.default.webcrypto});
`
)();
}
// //////////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////////
_sleep = async (duration) => {
await new Promise((s,j) => {setTimeout(() => {return s(true)},duration)});
}
// //////////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////////
//
// Function: base64ToArray
// What is this: Take a base64 string. Convert it to a Uint8Array...
//
// Arguments: strng: - base64 encoded string
//
// Returns: Uint8Array
// Notes:
//
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
base64ToArray(strng) {
return Uint8Array.from(atob(strng), (c) => c.charCodeAt(0));
}
// //////////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////////
//
// Function: arrayToBase64
// What is this: take a Uint8Array, make it a valid base64 string
//
// Arguments: ary: - Uint8Array
//
// Returns: Base64 String
// Notes:
//
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
arrayToBase64(utf8Bytes) {
// Split the bytes into smaller chunks to avoid call stack issues
const chunkSize = 8192;
const chunks = [];
for (let i = 0; i < utf8Bytes.length; i += chunkSize) {
const chunk = utf8Bytes.subarray(i, i + chunkSize);
chunks.push(String.fromCharCode.apply(null, chunk));
}
// Convert the bytes to a base64 string
const base64 = btoa(chunks.join(''));
return base64;
}
// //////////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////////
//
// Function: hmac (static) (async)
// What is this: Create a cryptographic signature for a piece of data given a *SHARED* secret.
// Similar to ECDSA - Except both parties have to have the secret-key in advance
// to make it work.
//
// Arguments: secret - this is the shared secret
// data - this is the string you're encrypting
//
// Returns: hex encoded 32 character string or something...(todo: check length - better def)
// Notes: https://stackoverflow.com/questions/47329132/how-to-get-hmac-with-crypto-web-api_47332317
//
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
HMAC = async (secret, data) => {
await this._sleep(0);
// To do work, we need to convert text to Uint8Arrays
let encoder = new TextEncoder("utf-8");
let encodedSecret = encoder.encode(secret);
let encodedData = encoder.encode(data);
// Create our HMAC Key
let key = await this._crypto.subtle.importKey(
"raw",
encodedSecret,
{ name: "HMAC", hash: { name: "SHA-256" } },
false,
["sign", "verify"]
);
// HMAC Sign our data with our HMAC Key
let sig = await this._crypto.subtle.sign("HMAC", key, encodedData);
// Turn the signature into an array; then into hex-text
// (todo: Maybe this is its own method...?)
//
let b = new Uint8Array(sig);
let str = Array.prototype.map
.call(b, (x) => ("00" + x.toString(16)).slice(-2))
.join("");
return str;
}
// //////////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////////
//
// Function: HASH (static) (async)
// What is this: The digest() method of the SubtleCrypto interface generates a digest of the given data.
// A digest is a short fixed-length value derived from some variable-length input.
// Cryptographic digests should exhibit collision-resistance, meaning that it's hard to come up
// with two different inputs that have the same digest value.
//
// Arguments: algo - this is the string you're hashing for
// data - This is the algorithm you're using to hash the data with (SHA-1, SHA-256, SHA-384, SHA-512)
//
// Returns: the hash of the data you provided as a base64 string
//
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
HASH = async (algo, data, len) => {
await this._sleep(0);
let hash = await this._crypto.subtle.digest(algo, new TextEncoder().encode(data));
let ary = new Uint8Array(hash);
let outAry;
if(len){
// initialize outAry to the desired size
outAry = new Uint8Array(len,0);
let min = Math.min(len, ary.length);
let max = Math.max(len, ary.length);
for(var i = 0; i < max; i++){
outAry[i%len] = outAry[i%len] ^ ary[i%ary.length];
}
} else {
outAry = ary;
}
return this.arrayToBase64(new Uint8Array(outAry));
}
// //////////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////////
//
//
// Function: PASSWORD_ENCRYPT
// What is this: Dead simple method to encrypt a piece of data with a password
// that can later be decrypted needing only that password
//
// Arguments: password: string; plaintext string of user's password
// base64data: string; what you want to encrypt
//
// Returns: base64 encoded, stringified object containing the AES key used
// to encrypt the data, and the ciphertext itself
// Notes:
//
//
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
PASSWORD_ENCRYPT = async(password, base64data) => {
await this._sleep(0);
for(let i = 0; i < 10; i++){
password = await this.HASH("SHA-512", password);
}
let passwordHash = btoa(password);
let aes = await this.AESMakeKey(true);
let output = await this.AESEncrypt(aes, base64data, passwordHash);
return btoa(JSON.stringify({ciphertext: output.ciphertext, aes}));
}
// //////////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////////
//
//
// Function: PASSWORD_DECRYPT
// What is this: Counterparty to PASSWORD_ENCRYPT. Give it a password, and
// the encrypted data from PASSWORD_ENCRYPT; it should give you
// the initial plaintext...
//
// Arguments: password: string; plaintext string of user's password
// base64data: password-data
//
// Returns: plaintext
//
// Notes:
//
//
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
PASSWORD_DECRYPT = async(password, base64data) => {
await this._sleep(0);
for(let i = 0; i < 10; i++){
password = await this.HASH("SHA-512", password);
}
let passwordHash = btoa(password);
let encryptedDataObject = JSON.parse(atob(base64data));
let aes = await this.AESImportKey(encryptedDataObject.aes,false);
let ciphertext = encryptedDataObject.ciphertext;
let plaintext = await this.AESDecrypt(aes, passwordHash, ciphertext, true);
return plaintext;
}
// //////////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////////
//
// Function: AESMakeKey (async)
// What is this: Generate an AES Key and return its hex
//
// Arguments: *NONE*
//
// Returns: base64 string
// Notes:
//
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
AESMakeKey = async (exportable = true) => {
await this._sleep(0);
// 1.) Generate the Key
let key = await this._crypto.subtle.generateKey(
{ name: "AES-GCM", length: 256 },
exportable,
["encrypt", "decrypt"]
);
// 2.)
if(exportable){
//Return it as b64 if its exportable
let out = await this._crypto.subtle.exportKey("raw", key);
return this.arrayToBase64(new Uint8Array(out));
} else {
// else return the CryptoKey Object
return key;
}
};
// //////////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////////
//
// Function: AESImportKey (async)
// What is this: Generate an AES Key and return its hex
//
// Arguments: base64 string
//
// Returns: Live AES Key
// Notes:
//
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
AESImportKey = async (aes_key, exportable = true) => {
await this._sleep(0);
if(aes_key instanceof this._crypto.CryptoKey){
return aes_key;
} else {
// 1.) Generate the Key
return await this._crypto.subtle.importKey(
"raw",
this.base64ToArray(aes_key).buffer,
"AES-GCM",
exportable,
["encrypt", "decrypt"]
);
}
};
// //////////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////////
//
// Function: AESEncrypt (async)
// What is this: Given
//
// Arguments: key: base64 AES-key
// data: uInt8Array
//
// Returns: base64 string
// Notes:
//
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
async AESEncrypt(base_64_key, base_64_data, base_64_nonce = false) {
await this._sleep(0);
// 0.) Pass Key to
let aes_key = await this.AESImportKey(base_64_key);
// 3.) Create a nonce why not?
let nonce;
if(base_64_nonce){
nonce = this.base64ToArray(base_64_nonce);
} else {
nonce = this._crypto.getRandomValues(new Uint8Array(16));
}
// 4.) encrypt our data
let encrypted = await this._crypto.subtle.encrypt(
{ name: "AES-GCM", iv: nonce },
aes_key,
this.base64ToArray(base_64_data)
);
// 5.) Base64 and return our data...
return {
ciphertext: this.arrayToBase64(new Uint8Array(encrypted)),
iv: this.arrayToBase64(nonce),
};
}
// //////////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////////
//
// Function: AESDecrypt (async)
// What is this: Given
//
// Arguments: key: base64 AES-key
// nonce: base64 of the nonce used at encryption (ok if it is public)
// ciphertext: base64 of what's been encoded
//
// Returns: base64 string
// Notes:
//
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
async AESDecrypt(base_64_key, base_64_nonce, base_64_cipher, returnText = false) {
await this._sleep(0);
// 1.) Convert out from base64 to array
let aes_key = await this.AESImportKey(base_64_key);
let nonce_ary = this.base64ToArray(base_64_nonce);
let cipher_ary = this.base64ToArray(base_64_cipher);
let decrypted;
// 3.) Decrypt
decrypted = await this._crypto.subtle.decrypt(
{ name: "AES-GCM", iv: nonce_ary },
aes_key,
cipher_ary
);
if(!returnText){
return decrypted;
} else {
decrypted = new Uint8Array(decrypted);
decrypted = new TextDecoder().decode(decrypted);
return decrypted;
}
}
// //////////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////////
//
// Function: EcMakeCryptKeys (async)
// What is this: Given
//
// Arguments: none
//
// Returns: object containing public and private key pair
// Notes:
//
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
EcMakeCryptKeys = async (exportable = true) => {
await this._sleep(0);
// Step 1) Create ECDH KeyS
let keys = await this._crypto.subtle.generateKey(
{ name: "ECDH", namedCurve: "P-256" },
exportable,
["deriveKey","deriveBits"]
);
// Step 2) Export keys to SPKI|PKCS8|JWK|RAW format
let exportKeys;
if(exportable){
exportKeys = await Promise.all([
this._crypto.subtle.exportKey("spki", keys.publicKey).then((key) => {
return this.arrayToBase64(new Uint8Array(key));
}),
this._crypto.subtle.exportKey("pkcs8", keys.privateKey).then((key) => {
return this.arrayToBase64(new Uint8Array(key));
}),
this._crypto.subtle.exportKey("jwk", keys.publicKey).then((key) => {
return (key);
}),
this._crypto.subtle.exportKey("jwk", keys.privateKey).then((key) => {
return (key);
}),
this._crypto.subtle.exportKey("raw", keys.publicKey).then((key) => {
return this.arrayToBase64( new Uint8Array(key));
}),
this._crypto.subtle.exportKey("raw", keys.publicKey).then((key) => {
return this.arrayToBase64( new Uint8Array(key).slice(1,1000));
})
]);
} else {
exportKeys = await Promise.all([
//
this._crypto.subtle.exportKey("spki", keys.publicKey).then((key) => {
return this.arrayToBase64(new Uint8Array(key));
}),
//
(new Promise((s,j) => {return s(keys.privateKey)})),
//
this._crypto.subtle.exportKey("raw", keys.publicKey).then((key) => {
return this.arrayToBase64( new Uint8Array(key));
}),
//
this._crypto.subtle.exportKey("raw", keys.publicKey).then((key) => {
return this.arrayToBase64( new Uint8Array(key).slice(1,1000));
})
]);
}
if(exportable){
return {
publicKey: exportKeys[0],
privateKey: exportKeys[1],
jwkPublicKey: exportKeys[2],
jwkPrivateKey: exportKeys[3],
rawPublicKey: exportKeys[4],
rawPublicKeyLite: exportKeys[5]
};
} else {
return {
publicKey: exportKeys[0],
privateKey: exportKeys[1],
rawPublicKey: exportKeys[2],
rawPublicKeyLite: exportKeys[3]
};
}
// Step 3) Convert the keys to base64 and return...
};
// //////////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////////
//
// Function: EcEncrypt (async)
// What is this: Encrypt Uint8Data with 2 SPKI-Encoded ECDH Keys.
// ---
// Basically it does the dirty work of:
// - convert base64 keys to live keys
// - creating AES key from live keys
// - encrypting data with AES Key
// - return base64 ciphertext and nonce
//
//
// Arguments: base64privateKey: string;
// base64publicKey: string;
// base64data: string;
//
// Returns: object containing public and private key pair
// Notes:
//
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
EcEncrypt = async (b64Private, b64Public, b64data) => {
await this._sleep(0);
// 1.) convert the given keys to real keys in the most
// generic way possible...
let publicKey = await this.EcdhConvertKey(b64Public);
let privateKey = await this.EcdhConvertKey(b64Private);
// 2.) generate shared key
let aes_key = await this._crypto.subtle.deriveKey(
{ name: "ECDH", public: publicKey },
privateKey,
{ name: "AES-GCM", length: 256 },
false,
["encrypt", "decrypt"]
)
// 3.) Work smarter, not harder, dummy...
return await this.AESEncrypt(aes_key, b64data);
};
// //////////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////////
//
// Function: EcDecrypt (async)
// What is this: Decrypt Uint8Data with 2 SPKI-Encoded ECDH Keys.
// ---
// Basically it does the dirty work of:
// - convert base64 keys to live keys
// - creating AES key from live keys
// - encrypting data with AES Key
// - return base64 ciphertext and nonce
//
//
// Arguments: base64privateKey: string;
// base64publicKey: string;
// base64nonce: string;
// base64data: string;
//
// Returns: object containing public and private key pair
// Notes:
//
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
EcDecrypt = async (b64Private, b64Public, b64Nonce, b64data, returnText = false) => {
// 1.) convert the given keys to real keys in the most
// generic way possible...
let publicKey = await this.EcdhConvertKey(b64Public);
let privateKey = await this.EcdhConvertKey(b64Private);
let nonce = this.base64ToArray(b64Nonce);
let data = this.base64ToArray(b64data);
let decrypted;
// 2.) generate shared key
let aes_key = await this._crypto.subtle.deriveKey(
{ name: "ECDH", public: publicKey },
privateKey,
{ name: "AES-GCM", length: 256 },
false,
["encrypt", "decrypt"]
);
// 3..) decrypt our data
const decryptedData = await this._crypto.subtle.decrypt(
{ name: "AES-GCM", iv: nonce },
aes_key,
data
);
if(!returnText){
return decryptedData;
} else {
decrypted = new Uint8Array(decryptedData);
decrypted = new TextDecoder().decode(decrypted);
return decrypted;
}
};
// //////////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////////
//
// Function: HKDFEncrypt (async)
// What is this: Encrypt Uint8Data with 2 SPKI-Encoded ECDH Keys.
// ---
// Basically it does the dirty work of:
// - convert base64 keys to live keys
// - creating AES key from live keys
// - encrypting data with AES Key
// - return base64 ciphertext and nonce
//
//
// Arguments: base64privateKey: string;
// base64publicKey: string;
// base64data: string;
//
// Returns: object containing public and private key pair
// Notes:
//
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
HKDFEncrypt = async (b64Private, b64Public, b64data) => {
await this._sleep(0);
// 1.) convert the given keys to real keys in the most
// generic way possible...
let publicKey = await this.EcdhConvertKey(b64Public);
let privateKey = await this.EcdhConvertKey(b64Private);
// 2.) generate shared secret for HKDF
//
let sharedSecret = await this._crypto.subtle.deriveBits({
"name": "ECDH",
"namedCurve": "P-256",
"public": publicKey
},privateKey,256);
// 3.) convert shared-secret into a key
//
let sharedSecretKey = await this._crypto.subtle.importKey(
"raw", sharedSecret,
{ "name": 'HKDF' },
false,
['deriveKey','deriveBits']
);
// 4.) create SALT
//
let salt = this._crypto.getRandomValues(new Uint8Array(16));
// 5.) convert the live-shared-secret-key into an aes key
//
let derivedKey = await this._crypto.subtle.deriveBits({
"name": 'HKDF',
"hash": 'SHA-256',
"salt": salt,
"info": new Uint8Array([])},
sharedSecretKey,256
);
//
// 6.)
// THIS SHOULD NOT BE THIS HARD!
//
// Convert the Key-Array to a live Key
let aes_key = await this._crypto.subtle.importKey(
"raw",
derivedKey,
"AES-GCM",
false,
["encrypt","decrypt"]
);
// 7.) Init Vector
//
//
let iv = this._crypto.getRandomValues(new Uint8Array(16));
// 7.) Encrypt
//
//
let encrypted = await this._crypto.subtle.encrypt(
{ name: "AES-GCM", iv: iv },
aes_key,
this.base64ToArray(b64data)
);
// 8.) Base64 and return our data...
return {
"ciphertext": this.arrayToBase64(new Uint8Array(encrypted)),
"salt": this.arrayToBase64(salt),
"iv": this.arrayToBase64(iv)
};
};
// //////////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////////
//
// Function: HKDFDecrypt (async)
// What is this: Decrypt Uint8Data with 2 SPKI-Encoded ECDH Keys.
// ---
// Basically it does the dirty work of:
// - convert base64 keys to live keys
// - creating AES key from live keys
// - encrypting data with AES Key
// - return base64 ciphertext and nonce
//
//
// Arguments: base64privateKey: string;
// base64publicKey: string;
// base64nonce: string;
// base64data: string;
//
// Returns: object containing public and private key pair
// Notes:
//
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
HKDFDecrypt = async (b64Private, b64Public, b64Salt, b64iv, b64data, returnText = false) => {
await this._sleep(0);
// 1.) convert the given keys to real keys in the most
// generic way possible...
let publicKey = await this.EcdhConvertKey(b64Public);
let privateKey = await this.EcdhConvertKey(b64Private);
let salt = this.base64ToArray(b64Salt);
let iv = this.base64ToArray(b64iv);
let data = this.base64ToArray(b64data);
let decrypted;
// 2.) generate shared secret for HKDF
//
let sharedSecret = await this._crypto.subtle.deriveBits({
"name": "ECDH",
"namedCurve": "P-256",
"public": publicKey
},privateKey,256);
// 3.) convert shared-secret into a key
//
let sharedSecretKey = await this._crypto.subtle.importKey(
"raw", sharedSecret,
{ "name": 'HKDF' },
false,
['deriveKey','deriveBits']
);
// 4.) convert the live-shared-secret-key into an aes key
//
let derivedKey = await this._crypto.subtle.deriveBits({
"name": 'HKDF',
"hash": 'SHA-256',
"salt": salt,
"info": new Uint8Array([])},
sharedSecretKey,256
);
//
// 5.)
// Convert the Key-Array to a live Key
let aes_key = await this._crypto.subtle.importKey(
"raw",
derivedKey,
"AES-GCM",
false,
["encrypt","decrypt"]
);
// 6.) decrypt our data
//
let aes_data;
try{
aes_data = await this._crypto.subtle.decrypt(
{ name: "AES-GCM", iv: iv },
aes_key,
data
);
} catch(e){
console.log({name: e.name, stack: e.stack, message: e.message});
throw e;
}
if(!returnText){
return aes_data;
} else {
decrypted = new Uint8Array(aes_data);
decrypted = new TextDecoder().decode(decrypted);
return decrypted;
}
};
// //////////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////////
//
// Function: EcMakeSigKeys (async)
// What is this: Given
//
// Arguments: none
//
// Returns: object containing public and private key pair
// Notes:
//
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
EcMakeSigKeys = async (exportable = true) => {
await this._sleep(0);
// Step 1) Create ECDSA KeyS
let keys = await this._crypto.subtle.generateKey(
{ name: "ECDSA", namedCurve: "P-256" },
exportable,
["sign","verify"]
);
let b64Keys;
// Step 2a) IF EXTRACTABLE: Export keys to SPKI|PKCS8 format
if(exportable){
b64Keys = await Promise.all([
this._crypto.subtle.exportKey("spki", keys.publicKey).then((key) => {
return this.arrayToBase64(new Uint8Array(key));
}),
this._crypto.subtle.exportKey("pkcs8", keys.privateKey).then((key) => {
return this.arrayToBase64(new Uint8Array(key));
})
]);
return { publicKey: b64Keys[0], privateKey: b64Keys[1] };
} else {
// Step 2b) NOT NOT NOT EXTRACTABLE: Export just the public key
b64Keys = await Promise.all([
this._crypto.subtle.exportKey("spki", keys.publicKey).then((key) => {
return this.arrayToBase64(new Uint8Array(key));
})
]);
return { publicKey: b64Keys[0], privateKey: keys.privateKey };
}
};
// //////////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////////
//
// Function: EcSignData (async)
// What is this: Create a crypto-signature from a private key and data
//
// Arguments: base64privateKey: string;
// data: Uint8Array;
//
// Returns: base64 encoded signature
// Notes:
//
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
EcSignData = async (b64PrivateKey, b64data) => {
await this._sleep(0);
// 1.) convert the given keys to real keys
let privateKey = await this.EcdsaConvertKey(b64PrivateKey);
// 2.) sign the data with the live key
let signature = await this._crypto.subtle.sign({"name": "ECDSA", "hash": {"name": "SHA-256"}}, privateKey, this.base64ToArray(b64data));
// 3.) Base64 and return our data...
return await this.arrayToBase64(new Uint8Array(signature));
};
// //////////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////////
//
// Function: EcVerifySig (async)
// What is this: Given a public key, some data, and a signature; prove the
// signature came from the data and the public key
//
// Arguments: base64PublicKey: string;
// data: Uint8Array;
//
// Returns: base64 encoded signature
// Notes:
//
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
EcVerifySig = async (b64PublicKey, b64Signature, b64data) => {
await this._sleep(0);
// 1.) convert the given keys to real keys
let publicKey = await this.EcdsaConvertKey(b64PublicKey);
// 2.) Convert the signature to an array
let signature = this.base64ToArray(b64Signature);
// 3.) verify the data with the live key
return await this._crypto.subtle.verify({"name": "ECDSA", "hash": {"name": "SHA-256"}}, publicKey, signature, this.base64ToArray(b64data));
};
// //////////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////////
//
// Function: EzConvertKey (base64key)
// What is this: Sloppy AF function to try converting random data into a key
// until something works...
//
// Arguments: none
//
// Returns: hopefully a live key...probably an error and an hour of debugging.
// Notes:
//
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
EcdhConvertKey = async (unknown_key) => {