-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathtestrunner.dart
1487 lines (1340 loc) · 47.7 KB
/
testrunner.dart
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
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import 'dart:convert';
import 'dart:math';
import 'dart:async';
import 'package:meta/meta.dart';
import 'package:webcrypto/webcrypto.dart';
import 'detected_runtime.dart';
import 'ffibonacci_chunked_stream.dart';
import 'utils.dart';
import 'lipsum.dart';
import 'err_stack_stub.dart' if (dart.library.ffi) 'err_stack_ffi.dart';
// Export utilities necessary for implementing a `TestRunner`.
export 'utils.dart' show hashFromJson, curveFromJson;
List<int>? _optionalBase64Decode(dynamic data) =>
data == null ? null : base64.decode(data as String);
Map<String, dynamic>? _optionalStringMapDecode(dynamic data) =>
data == null ? null : (data as Map).cast<String, dynamic>();
String? _optionalBase64Encode(List<int>? data) =>
data == null ? null : base64.encode(data);
@sealed
class _TestCase {
final String name;
// Obtain a keyPair from import or key generation
final Map<String, dynamic>? generateKeyParams;
final List<int>? privateRawKeyData;
final List<int>? privatePkcs8KeyData;
final Map<String, dynamic>? privateJsonWebKeyData;
final List<int>? publicRawKeyData;
final List<int>? publicSpkiKeyData;
final Map<String, dynamic>? publicJsonWebKeyData;
// Plaintext to be signed, (always required)
final List<int>? plaintext;
// Signature to be verified (invalid, if generateKeyParams != null)
final List<int>? signature;
// Ciphertext of plaintext (invalid, if generateKeyParams != null)
final List<int>? ciphertext;
// Bits derived using deriveBits (invalid, if generateKeyParams != null)
final List<int>? derivedBits;
// Number of bits to derive.
final int? derivedLength;
// Parameters for key import (always required)
final Map<String, dynamic>? importKeyParams;
// Parameters for sign/verify (required, if there is a signature)
final Map<String, dynamic>? signVerifyParams;
// Parameters for encrypt/decrypt (required, if there is a ciphertext)
final Map<String, dynamic>? encryptDecryptParams;
// Parameters for deriveBits (required, if there is a derivedBits)
final Map<String, dynamic>? deriveParams;
_TestCase(
this.name, {
this.generateKeyParams,
this.privateRawKeyData,
this.privatePkcs8KeyData,
this.privateJsonWebKeyData,
this.publicRawKeyData,
this.publicSpkiKeyData,
this.publicJsonWebKeyData,
this.plaintext,
this.signature,
this.ciphertext,
this.derivedBits,
this.derivedLength,
this.importKeyParams,
this.signVerifyParams,
this.encryptDecryptParams,
this.deriveParams,
});
factory _TestCase.fromJson(Map json) {
return _TestCase(
json['name'] as String,
generateKeyParams: _optionalStringMapDecode(json['generateKeyParams']),
privateRawKeyData: _optionalBase64Decode(json['privateRawKeyData']),
privatePkcs8KeyData: _optionalBase64Decode(json['privatePkcs8KeyData']),
privateJsonWebKeyData:
_optionalStringMapDecode(json['privateJsonWebKeyData']),
publicRawKeyData: _optionalBase64Decode(json['publicRawKeyData']),
publicSpkiKeyData: _optionalBase64Decode(json['publicSpkiKeyData']),
publicJsonWebKeyData:
_optionalStringMapDecode(json['publicJsonWebKeyData']),
plaintext: _optionalBase64Decode(json['plaintext']),
signature: _optionalBase64Decode(json['signature']),
ciphertext: _optionalBase64Decode(json['ciphertext']),
derivedBits: _optionalBase64Decode(json['derivedBits']),
derivedLength: json['derivedLength'] as int?,
importKeyParams: _optionalStringMapDecode(json['importKeyParams']),
signVerifyParams: _optionalStringMapDecode(json['signVerifyParams']),
encryptDecryptParams:
_optionalStringMapDecode(json['encryptDecryptParams']),
deriveParams: _optionalStringMapDecode(json['deriveParams']),
);
}
Map<String, dynamic> toJson() {
return {
'name': name,
'generateKeyParams': generateKeyParams,
'privateRawKeyData': _optionalBase64Encode(privateRawKeyData),
'privatePkcs8KeyData': _optionalBase64Encode(privatePkcs8KeyData),
'privateJsonWebKeyData': privateJsonWebKeyData,
'publicRawKeyData': _optionalBase64Encode(publicRawKeyData),
'publicSpkiKeyData': _optionalBase64Encode(publicSpkiKeyData),
'publicJsonWebKeyData': publicJsonWebKeyData,
'plaintext': _optionalBase64Encode(plaintext),
'signature': _optionalBase64Encode(signature),
'ciphertext': _optionalBase64Encode(ciphertext),
'derivedBits': _optionalBase64Encode(derivedBits),
'derivedLength': derivedLength,
'importKeyParams': importKeyParams,
'signVerifyParams': signVerifyParams,
'encryptDecryptParams': encryptDecryptParams,
'deriveParams': deriveParams,
}..removeWhere((_, v) => v == null);
}
}
/// Function for importing pkcs8, spki, or raw key.
typedef ImportKeyFn<T> = Future<T> Function(
List<int> keyData,
Map<String, dynamic> keyImportParams,
);
/// Function for exporting pkcs8, spki or raw key.
typedef ExportKeyFn<T> = Future<List<int>> Function(T key);
/// Function for importing JWK key.
typedef ImportJsonWebKeyKeyFn<T> = Future<T> Function(
Map<String, dynamic> jsonWebKeyData,
Map<String, dynamic> keyImportParams,
);
/// Function for exporting JWK key.
typedef ExportJsonWebKeyKeyFn<T> = Future<Map<String, dynamic>> Function(T key);
/// Function for generating a key.
typedef GenerateKeyFn<T> = Future<T> Function(
Map<String, dynamic> generateKeyPairParams,
);
/// Function for signing [data] using [key].
typedef SignBytesFn<T> = Future<List<int>> Function(
T key,
List<int> data,
Map<String, dynamic> signParams,
);
/// Function for signing [data] using [key].
typedef SignStreamFn<T> = Future<List<int>> Function(
T key,
Stream<List<int>> data,
Map<String, dynamic> signParams,
);
/// Function for verifying [data] using [key].
typedef VerifyBytesFn<T> = Future<bool> Function(
T key,
List<int> signature,
List<int> data,
Map<String, dynamic> verifyParams,
);
/// Function for verifying [data] using [key].
typedef VerifyStreamFn<T> = Future<bool> Function(
T key,
List<int> signature,
Stream<List<int>> data,
Map<String, dynamic> verifyParams,
);
/// Function for encrypting or a function for decrypting [data] using [key].
typedef EncryptOrDecryptBytesFn<T> = Future<List<int>> Function(
T key,
List<int> data,
Map<String, dynamic> encryptOrDecryptParams,
);
/// Function for encrypting or a function for decrypting [data] using [key].
typedef EncryptOrDecryptStreamFn<T> = Stream<List<int>> Function(
T key,
Stream<List<int>> data,
Map<String, dynamic> encryptOrDecryptParams,
);
typedef DeriveBitsFn<T> = Future<List<int>> Function(
T keyOrKeyPair,
int length,
Map<String, dynamic> deriveParams,
);
class _KeyPair<S, T> implements KeyPair<S, T> {
@override
final S privateKey;
@override
final T publicKey;
_KeyPair({required this.privateKey, required this.publicKey});
}
@sealed
class TestRunner<PrivateKey, PublicKey> {
final String algorithm;
/// True, if private is a secret key and there is no public key.
final bool _isSymmetric;
final ImportKeyFn<PrivateKey>? _importPrivateRawKey;
final ExportKeyFn<PrivateKey>? _exportPrivateRawKey;
final ImportKeyFn<PrivateKey>? _importPrivatePkcs8Key;
final ExportKeyFn<PrivateKey>? _exportPrivatePkcs8Key;
final ImportJsonWebKeyKeyFn<PrivateKey>? _importPrivateJsonWebKey;
final ExportJsonWebKeyKeyFn<PrivateKey>? _exportPrivateJsonWebKey;
final ImportKeyFn<PublicKey>? _importPublicRawKey;
final ExportKeyFn<PublicKey>? _exportPublicRawKey;
final ImportKeyFn<PublicKey>? _importPublicSpkiKey;
final ExportKeyFn<PublicKey>? _exportPublicSpkiKey;
final ImportJsonWebKeyKeyFn<PublicKey>? _importPublicJsonWebKey;
final ExportJsonWebKeyKeyFn<PublicKey>? _exportPublicJsonWebKey;
final GenerateKeyFn<KeyPair<PrivateKey, PublicKey>> _generateKeyPair;
final SignBytesFn<PrivateKey>? _signBytes;
final SignStreamFn<PrivateKey>? _signStream;
final VerifyBytesFn<PublicKey>? _verifyBytes;
final VerifyStreamFn<PublicKey>? _verifyStream;
final EncryptOrDecryptBytesFn<PublicKey>? _encryptBytes;
final EncryptOrDecryptStreamFn<PublicKey>? _encryptStream;
final EncryptOrDecryptBytesFn<PrivateKey>? _decryptBytes;
final EncryptOrDecryptStreamFn<PrivateKey>? _decryptStream;
final DeriveBitsFn<KeyPair<PrivateKey, PublicKey>>? _deriveBits;
final List<Map<dynamic, dynamic>> _testData;
TestRunner._({
required bool isSymmetric,
required this.algorithm,
ImportKeyFn<PrivateKey>? importPrivateRawKey,
ExportKeyFn<PrivateKey>? exportPrivateRawKey,
ImportKeyFn<PrivateKey>? importPrivatePkcs8Key,
ExportKeyFn<PrivateKey>? exportPrivatePkcs8Key,
ImportJsonWebKeyKeyFn<PrivateKey>? importPrivateJsonWebKey,
ExportJsonWebKeyKeyFn<PrivateKey>? exportPrivateJsonWebKey,
ImportKeyFn<PublicKey>? importPublicRawKey,
ExportKeyFn<PublicKey>? exportPublicRawKey,
ImportKeyFn<PublicKey>? importPublicSpkiKey,
ExportKeyFn<PublicKey>? exportPublicSpkiKey,
ImportJsonWebKeyKeyFn<PublicKey>? importPublicJsonWebKey,
ExportJsonWebKeyKeyFn<PublicKey>? exportPublicJsonWebKey,
required GenerateKeyFn<KeyPair<PrivateKey, PublicKey>> generateKeyPair,
SignBytesFn<PrivateKey>? signBytes,
SignStreamFn<PrivateKey>? signStream,
VerifyBytesFn<PublicKey>? verifyBytes,
VerifyStreamFn<PublicKey>? verifyStream,
EncryptOrDecryptBytesFn<PublicKey>? encryptBytes,
EncryptOrDecryptStreamFn<PublicKey>? encryptStream,
EncryptOrDecryptBytesFn<PrivateKey>? decryptBytes,
EncryptOrDecryptStreamFn<PrivateKey>? decryptStream,
DeriveBitsFn<KeyPair<PrivateKey, PublicKey>>? deriveBits,
Iterable<Map<dynamic, dynamic>>? testData,
}) : _isSymmetric = isSymmetric,
_importPrivateRawKey = importPrivateRawKey,
_exportPrivateRawKey = exportPrivateRawKey,
_importPrivatePkcs8Key = importPrivatePkcs8Key,
_exportPrivatePkcs8Key = exportPrivatePkcs8Key,
_importPrivateJsonWebKey = importPrivateJsonWebKey,
_exportPrivateJsonWebKey = exportPrivateJsonWebKey,
_importPublicRawKey = importPublicRawKey,
_exportPublicRawKey = exportPublicRawKey,
_importPublicSpkiKey = importPublicSpkiKey,
_exportPublicSpkiKey = exportPublicSpkiKey,
_importPublicJsonWebKey = importPublicJsonWebKey,
_exportPublicJsonWebKey = exportPublicJsonWebKey,
_generateKeyPair = generateKeyPair,
_signBytes = signBytes,
_signStream = signStream,
_verifyBytes = verifyBytes,
_verifyStream = verifyStream,
_encryptBytes = encryptBytes,
_encryptStream = encryptStream,
_decryptBytes = decryptBytes,
_decryptStream = decryptStream,
_deriveBits = deriveBits,
_testData = List.from(testData ?? <Map<dynamic, dynamic>>[]) {
_validate();
}
/// Create [TestRunner] for an asymmetric primitive.
static TestRunner<PrivateKey, PublicKey> asymmetric<PrivateKey, PublicKey>({
required String algorithm,
ImportKeyFn<PrivateKey>? importPrivateRawKey,
ExportKeyFn<PrivateKey>? exportPrivateRawKey,
ImportKeyFn<PrivateKey>? importPrivatePkcs8Key,
ExportKeyFn<PrivateKey>? exportPrivatePkcs8Key,
ImportJsonWebKeyKeyFn<PrivateKey>? importPrivateJsonWebKey,
ExportJsonWebKeyKeyFn<PrivateKey>? exportPrivateJsonWebKey,
ImportKeyFn<PublicKey>? importPublicRawKey,
ExportKeyFn<PublicKey>? exportPublicRawKey,
ImportKeyFn<PublicKey>? importPublicSpkiKey,
ExportKeyFn<PublicKey>? exportPublicSpkiKey,
ImportJsonWebKeyKeyFn<PublicKey>? importPublicJsonWebKey,
ExportJsonWebKeyKeyFn<PublicKey>? exportPublicJsonWebKey,
required GenerateKeyFn<KeyPair<PrivateKey, PublicKey>> generateKeyPair,
SignBytesFn<PrivateKey>? signBytes,
SignStreamFn<PrivateKey>? signStream,
VerifyBytesFn<PublicKey>? verifyBytes,
VerifyStreamFn<PublicKey>? verifyStream,
EncryptOrDecryptBytesFn<PublicKey>? encryptBytes,
EncryptOrDecryptStreamFn<PublicKey>? encryptStream,
EncryptOrDecryptBytesFn<PrivateKey>? decryptBytes,
EncryptOrDecryptStreamFn<PrivateKey>? decryptStream,
DeriveBitsFn<KeyPair<PrivateKey, PublicKey>>? deriveBits,
Iterable<Map<dynamic, dynamic>>? testData,
}) {
return TestRunner._(
isSymmetric: false,
algorithm: algorithm,
importPrivateRawKey: importPrivateRawKey,
exportPrivateRawKey: exportPrivateRawKey,
importPrivatePkcs8Key: importPrivatePkcs8Key,
exportPrivatePkcs8Key: exportPrivatePkcs8Key,
importPrivateJsonWebKey: importPrivateJsonWebKey,
exportPrivateJsonWebKey: exportPrivateJsonWebKey,
importPublicRawKey: importPublicRawKey,
exportPublicRawKey: exportPublicRawKey,
importPublicSpkiKey: importPublicSpkiKey,
exportPublicSpkiKey: exportPublicSpkiKey,
importPublicJsonWebKey: importPublicJsonWebKey,
exportPublicJsonWebKey: exportPublicJsonWebKey,
generateKeyPair: generateKeyPair,
signBytes: signBytes,
signStream: signStream,
verifyBytes: verifyBytes,
verifyStream: verifyStream,
encryptBytes: encryptBytes,
encryptStream: encryptStream,
decryptBytes: decryptBytes,
decryptStream: decryptStream,
deriveBits: deriveBits,
testData: testData,
);
}
/// Create [TestRunner] for an symmetric primitive.
///
/// This just creates a [TestRunner] where public and private key have the
/// same type. This may give rise to a few unnecessary test cases as
/// import/export of public and private key
static TestRunner<PrivateKey, PrivateKey> symmetric<PrivateKey>({
required String algorithm,
ImportKeyFn<PrivateKey>? importPrivateRawKey,
ExportKeyFn<PrivateKey>? exportPrivateRawKey,
ImportKeyFn<PrivateKey>? importPrivatePkcs8Key,
ExportKeyFn<PrivateKey>? exportPrivatePkcs8Key,
ImportJsonWebKeyKeyFn<PrivateKey>? importPrivateJsonWebKey,
ExportJsonWebKeyKeyFn<PrivateKey>? exportPrivateJsonWebKey,
required GenerateKeyFn<PrivateKey> generateKey,
SignBytesFn<PrivateKey>? signBytes,
SignStreamFn<PrivateKey>? signStream,
VerifyBytesFn<PrivateKey>? verifyBytes,
VerifyStreamFn<PrivateKey>? verifyStream,
EncryptOrDecryptBytesFn<PrivateKey>? encryptBytes,
EncryptOrDecryptStreamFn<PrivateKey>? encryptStream,
EncryptOrDecryptBytesFn<PrivateKey>? decryptBytes,
EncryptOrDecryptStreamFn<PrivateKey>? decryptStream,
DeriveBitsFn<PrivateKey>? deriveBits,
Iterable<Map<dynamic, dynamic>>? testData,
}) {
return TestRunner._(
isSymmetric: true,
algorithm: algorithm,
importPrivateRawKey: importPrivateRawKey,
exportPrivateRawKey: exportPrivateRawKey,
importPrivatePkcs8Key: importPrivatePkcs8Key,
exportPrivatePkcs8Key: exportPrivatePkcs8Key,
importPrivateJsonWebKey: importPrivateJsonWebKey,
exportPrivateJsonWebKey: exportPrivateJsonWebKey,
generateKeyPair: (params) async {
final k = await generateKey(params);
return _KeyPair(privateKey: k, publicKey: k);
},
signBytes: signBytes,
signStream: signStream,
verifyBytes: verifyBytes,
verifyStream: verifyStream,
encryptBytes: encryptBytes,
encryptStream: encryptStream,
decryptBytes: decryptBytes,
decryptStream: decryptStream,
deriveBits: deriveBits == null
? null
: (
KeyPair<PrivateKey, PrivateKey> pair,
int length,
Map<String, dynamic> deriveParams,
) async {
final a = await deriveBits(pair.privateKey, length, deriveParams);
final b = await deriveBits(pair.publicKey, length, deriveParams);
check(equalBytes(a, b), 'expected both keys to derive the same');
return a;
},
testData: testData,
);
}
void _validate() {
// Check that we have verify if we have sign
check((_signBytes != null) == (_verifyBytes != null));
check((_signStream != null) == (_verifyStream != null));
// If we can sign streams, we should also be able to sign bytes
if (_signStream != null) {
check(_signBytes != null);
}
// Check that we have decrypt if we have encrypt
check((_encryptBytes != null) == (_decryptBytes != null));
check((_encryptStream != null) == (_decryptStream != null));
// If we can encrypt streams, we should also be able to encrypt bytes
if (_encryptStream != null) {
check(_encryptBytes != null);
}
// Must have one priate key import format.
check(_importPrivateRawKey != null ||
_importPrivatePkcs8Key != null ||
_importPrivateJsonWebKey != null);
if (_isSymmetric) {
// if symmetric we have no methods for importing public keys
check(_importPublicRawKey == null);
check(_importPublicSpkiKey == null);
check(_importPublicJsonWebKey == null);
} else {
// Must have one public key import format.
check(_importPublicRawKey != null ||
_importPublicSpkiKey != null ||
_importPublicJsonWebKey != null);
}
// Export-only and import-only formats do not make sense
check(
(_importPrivateRawKey != null) == (_exportPrivateRawKey != null),
);
check(
(_importPrivatePkcs8Key != null) == (_exportPrivatePkcs8Key != null),
);
check(
(_importPrivateJsonWebKey != null) == (_exportPrivateJsonWebKey != null),
);
check(
(_importPublicRawKey != null) == (_exportPublicRawKey != null),
);
check(
(_importPublicSpkiKey != null) == (_exportPublicSpkiKey != null),
);
check(
(_importPublicJsonWebKey != null) == (_exportPublicJsonWebKey != null),
);
// Check all test cases
for (final data in _testData) {
final c = _TestCase.fromJson(data);
try {
_validateTestCase(this, c);
} catch (e) {
log('Invalid test case: $c');
rethrow;
}
}
}
Future<Map<String, dynamic>> generate({
required Map<String, dynamic> generateKeyParams,
required Map<String, dynamic> importKeyParams,
Map<String, dynamic> signVerifyParams = const {},
Map<String, dynamic> encryptDecryptParams = const {},
Map<String, dynamic> deriveParams = const {},
String plaintextTemplate = libsum,
int minPlaintext = 8,
int maxPlaintext = libsum.length,
int minDeriveLength = 4,
int maxDeriveLength = 512,
}) async {
check(minPlaintext <= maxPlaintext);
check(maxPlaintext <= plaintextTemplate.length);
final ts = DateTime.now().toIso8601String().split('.').first; // drop secs
final name = 'generated at $ts';
log('generating key-pair');
final pair = await _generateKeyPair(generateKeyParams);
final privateKey = pair.privateKey;
final publicKey = pair.publicKey;
check(privateKey != null);
check(publicKey != null);
List<int>? plaintext;
if (_signBytes != null || _encryptBytes != null) {
log('picking plaintext');
final rng = Random.secure();
final N = rng.nextInt(maxPlaintext - minPlaintext) + minPlaintext;
final offset = rng.nextInt(plaintextTemplate.length - N);
plaintext = utf8.encode(plaintextTemplate.substring(
offset,
offset + N,
));
}
List<int>? signature;
final signBytes = _signBytes;
if (signBytes != null) {
log('creating signature');
signature = await signBytes(
pair.privateKey,
plaintext!,
signVerifyParams,
);
}
List<int>? ciphertext;
final encryptBytes = _encryptBytes;
if (encryptBytes != null) {
log('creating ciphertext');
ciphertext = await encryptBytes(
pair.publicKey,
plaintext!,
encryptDecryptParams,
);
}
int? derivedLength;
List<int>? derivedBits;
final deriveBits = _deriveBits;
if (deriveBits != null) {
log('picking derivedLength');
final rng = Random.secure();
derivedLength = maxDeriveLength == minDeriveLength
? maxDeriveLength
: rng.nextInt(maxDeriveLength - minDeriveLength) + minDeriveLength;
log('creating derivedBits');
derivedBits = await deriveBits(
pair,
derivedLength,
deriveParams,
);
}
Future<T?> optionalCall<S, T>(Future<T> Function(S)? fn, S v) async =>
fn != null ? await fn(v) : null;
final c = _TestCase(
name,
generateKeyParams: null, // omit generateKeyParams
privateRawKeyData: await optionalCall(_exportPrivateRawKey, privateKey),
privatePkcs8KeyData:
await optionalCall(_exportPrivatePkcs8Key, privateKey),
privateJsonWebKeyData:
await optionalCall(_exportPrivateJsonWebKey, privateKey),
publicRawKeyData: await optionalCall(_exportPublicRawKey, publicKey),
publicSpkiKeyData: await optionalCall(_exportPublicSpkiKey, publicKey),
publicJsonWebKeyData:
await optionalCall(_exportPublicJsonWebKey, publicKey),
plaintext: plaintext,
signature: signature,
ciphertext: ciphertext,
derivedBits: derivedBits,
importKeyParams: importKeyParams,
signVerifyParams: signVerifyParams,
encryptDecryptParams: encryptDecryptParams,
derivedLength: derivedLength,
deriveParams: deriveParams,
);
// Log the generated test case. This makes it easy to copy/paste the test
// case into test files.
final json = const JsonEncoder.withIndent(' ')
.convert(c.toJson())
.replaceAll('\n', '\n| ');
log('| $json');
return c.toJson();
}
/// Get test cases from [testData].
///
/// If no [testData] is given the `testData` given when the [TestRunner] was
/// created will be used.
///
/// Returns a list of tuples with test name and test function.
List<({String name, Future<void> Function() test})> tests({
Iterable<Map<dynamic, dynamic>>? testData,
}) {
final tests = <({String name, Future<void> Function() test})>[];
testData ??= _testData;
for (final data in testData) {
final c = _TestCase.fromJson(data);
_runTests(this, c, (String name, FutureOr<void> Function() fn) {
tests.add((
// Prefix test names
name: '$algorithm: ${c.name} -- $name',
test: () async {
// Check BoringSSL error stack if running with dart:ffi
await checkErrorStack(fn);
}
));
});
}
return tests;
}
}
/// Wraps a [test] function such that calls must always be ordered, and that
/// any subsequent tests fails, if a previous test has failed.
void Function(String name, FutureOr Function() fn) _withTestDependency(
void Function(String name, FutureOr Function() fn) test,
) {
var count = 0;
var next = 0;
return (String name, FutureOr Function() fn) {
final order = count++;
test(name, () async {
if (next != order) {
check(false, 'Test dependency failed.');
}
await fn();
next++;
});
};
}
/// Validate that the test case [c] is compatible with TestRunner [r].
void _validateTestCase<PrivateKey, PublicKey>(
TestRunner<PrivateKey, PublicKey> r,
_TestCase c,
) {
final hasPrivateKey = c.privateRawKeyData != null ||
c.privatePkcs8KeyData != null ||
c.privateJsonWebKeyData != null;
final hasPublicKey = c.publicRawKeyData != null ||
c.publicSpkiKeyData != null ||
c.publicJsonWebKeyData != null;
// Test that we have keys to import or generate some.
if (r._isSymmetric) {
check(!hasPublicKey);
check(
c.generateKeyParams != null || hasPrivateKey,
'A key must be generated or imported',
);
} else {
check(
c.generateKeyParams != null || (hasPrivateKey && hasPublicKey),
'A key-pair must be generated or imported',
);
}
check(
c.generateKeyParams == null ||
(c.signature == null && c.ciphertext == null && c.derivedBits == null),
'Cannot verify signature/ciphertext/derivedBits for a generated key-pair',
);
check(
c.plaintext != null || (r._signBytes == null && r._encryptBytes == null),
'Cannot sign/encrypt without plaintext',
);
check(c.importKeyParams != null);
check((c.signVerifyParams != null) == (r._signBytes != null));
check((c.encryptDecryptParams != null) == (r._encryptBytes != null));
check((c.deriveParams != null) == (r._deriveBits != null));
if (c.signature != null) {
check(r._signBytes != null);
}
if (c.ciphertext != null) {
check(r._encryptBytes != null);
}
if (c.derivedBits != null) {
check(r._deriveBits != null);
}
if (r._deriveBits != null) {
check(c.derivedLength != null);
}
// Check that data matches the methods we have in the runner.
check(r._importPrivateRawKey != null || c.privateRawKeyData == null);
check(r._importPrivatePkcs8Key != null || c.privatePkcs8KeyData == null);
check(r._importPrivateJsonWebKey != null || c.privateJsonWebKeyData == null);
check(r._importPublicRawKey != null || c.publicRawKeyData == null);
check(r._importPublicSpkiKey != null || c.publicSpkiKeyData == null);
check(r._importPublicJsonWebKey != null || c.publicJsonWebKeyData == null);
}
void _runTests<PrivateKey, PublicKey>(
TestRunner<PrivateKey, PublicKey> r,
_TestCase c,
void Function(String name, FutureOr Function() fn) test,
) {
test = _withTestDependency(test);
test('validate test case', () => _validateTestCase(r, c));
try {
_validateTestCase(r, c);
} catch (_) {
// Don't register additional tests if the test-case is invalid!
return;
}
//------------------------------ Import or generate key-pair for testing
// Store publicKey and privateKey for use in later tests.
// If [_isSymmetric] is true, we still import the public and assign the
// private key to the public key.
PublicKey? publicKey;
PrivateKey? privateKey;
if (c.generateKeyParams != null) {
test('generateKeyPair()', () async {
final pair = await r._generateKeyPair(c.generateKeyParams!);
check(pair.privateKey != null);
check(pair.publicKey != null);
publicKey = pair.publicKey;
privateKey = pair.privateKey;
});
} else {
test('import key-pair', () async {
// Get a privateKey
if (c.privateRawKeyData != null) {
privateKey = await r._importPrivateRawKey!(
c.privateRawKeyData!,
c.importKeyParams!,
);
check(privateKey != null);
} else if (c.privatePkcs8KeyData != null) {
privateKey = await r._importPrivatePkcs8Key!(
c.privatePkcs8KeyData!,
c.importKeyParams!,
);
check(privateKey != null);
} else if (c.privateJsonWebKeyData != null) {
privateKey = await r._importPrivateJsonWebKey!(
c.privateJsonWebKeyData!,
c.importKeyParams!,
);
check(privateKey != null);
} else {
check(false, 'missing private key for importing');
}
// Get a publicKey
if (r._isSymmetric) {
// If symmetric algorithm we just use the private key.
publicKey = privateKey as PublicKey;
} else if (c.publicRawKeyData != null) {
publicKey = await r._importPublicRawKey!(
c.publicRawKeyData!,
c.importKeyParams!,
);
check(publicKey != null);
} else if (c.publicSpkiKeyData != null) {
publicKey = await r._importPublicSpkiKey!(
c.publicSpkiKeyData!,
c.importKeyParams!,
);
check(publicKey != null);
} else if (c.publicJsonWebKeyData != null) {
publicKey = await r._importPublicJsonWebKey!(
c.publicJsonWebKeyData!,
c.importKeyParams!,
);
check(publicKey != null);
} else {
check(false, 'missing public key for importing');
}
});
}
//------------------------------ Create a signature for testing
// Ensure that we have a signature for use in later test cases
List<int>? signature;
if (r._signBytes != null) {
if (c.signature != null) {
signature = c.signature;
} else {
test('create signature', () async {
signature = await r._signBytes!(
privateKey as PrivateKey,
c.plaintext!,
c.signVerifyParams!,
);
});
}
test('verify signature', () async {
check(
await r._verifyBytes!(
publicKey as PublicKey,
signature!,
c.plaintext!,
c.signVerifyParams!,
),
'failed to verify signature',
);
});
}
//------------------------------ Create a ciphertext for testing
List<int>? ciphertext;
if (r._encryptBytes != null) {
if (c.ciphertext != null) {
ciphertext = c.ciphertext!;
} else {
test('create ciphertext', () async {
ciphertext = await r._encryptBytes!(
publicKey as PublicKey,
c.plaintext!,
c.encryptDecryptParams!,
);
});
}
test('decrypt ciphertext', () async {
final text = await r._decryptBytes!(
privateKey as PrivateKey,
ciphertext!,
c.encryptDecryptParams!,
);
check(equalBytes(text, c.plaintext!), 'failed to decrypt ciphertext');
});
}
//------------------------------ Create derivedBits for testing
// Ensure that we have derivedBits for use in later test cases
List<int>? derivedBits;
if (r._deriveBits != null) {
if (c.derivedBits != null) {
derivedBits = c.derivedBits!;
} else {
test('create derivedBits', () async {
derivedBits = await r._deriveBits!(
_KeyPair(
privateKey: privateKey as PrivateKey,
publicKey: publicKey as PublicKey),
c.derivedLength!,
c.deriveParams!,
);
});
}
test('validated derivedBits', () async {
final derived = await r._deriveBits!(
_KeyPair(
privateKey: privateKey as PrivateKey,
publicKey: publicKey as PublicKey),
c.derivedLength!,
c.deriveParams!,
);
check(
equalBytes(derived, derivedBits!),
'failed to derivedBits are not consistent',
);
});
}
//------------------------------ Utilities for testing
//// Utility function to verify [sig] using [key].
Future<void> checkVerifyBytes(PublicKey key, List<int>? sig) async {
check(sig != null, 'signature cannot be null');
check(
await r._verifyBytes!(key, sig!, c.plaintext!, c.signVerifyParams!),
'failed to verify signature',
);
check(
!await r._verifyBytes!(
key,
flipFirstBits(sig),
c.plaintext!,
c.signVerifyParams!,
),
'verified an invalid signature',
);
if (c.plaintext!.isNotEmpty) {
check(
!await r._verifyBytes!(
key,
sig,
flipFirstBits(c.plaintext!),
c.signVerifyParams!,
),
'verified an invalid message',
);
}
}
/// Utility function to decrypt [ctext] using [key].
Future<void> checkDecryptBytes(PrivateKey key, List<int> ctext) async {
final text = await r._decryptBytes!(key, ctext, c.encryptDecryptParams!);
check(equalBytes(text, c.plaintext!), 'failed to decrypt ciphertext');
if (ctext.isNotEmpty) {
// If ciphertext is mangled some primitives like AES-GCM must throw
// others may return garbled plaintext.
try {
final invalidText = await r._decryptBytes!(
key,
flipFirstBits(ctext),
c.encryptDecryptParams!,
);
check(
!equalBytes(invalidText, c.plaintext!),
'decrypted an invalid ciphertext',
);
} on OperationError catch (e) {
check(e.toString() != '', 'expected some explanation');
}
}
}
/// Check if [signature] is sane.
Future<void> checkSignature(List<int>? signature) async {
check(signature != null, 'signature is null');
check(signature!.isNotEmpty, 'signature is empty');
await checkVerifyBytes(publicKey as PublicKey, signature);
}
/// Check if [ciphertext] is sane.
Future<void> checkCipherText(List<int>? ctext) async {
check(ctext != null, 'ciphtertext is null');
check(ctext!.isNotEmpty, 'ciphtertext is empty');
await checkDecryptBytes(privateKey as PrivateKey, ctext);
}
/// Check if [derived] is correct.
void checkDerivedBits(List<int>? derived) async {
check(derived != null, 'derivedBits is null');
check(derived!.isNotEmpty, 'derivedBits is empty');
check(equalBytes(derived, derivedBits!), 'derivedBits is not consistent');
}
/// Check if [publicKey] is sane.
Future<void> checkPublicKey(PublicKey? publicKey) async {
check(publicKey != null, 'publicKey is null');
if (r._signBytes != null) {
await checkVerifyBytes(publicKey as PublicKey, signature);
}
if (r._encryptBytes != null) {
final ctext = await r._encryptBytes!(
publicKey as PublicKey,
c.plaintext!,
c.encryptDecryptParams!,
);
await checkCipherText(ctext);
}
if (r._deriveBits != null) {
final derived = await r._deriveBits!(
_KeyPair(
privateKey: privateKey as PrivateKey,
publicKey: publicKey as PublicKey),
c.derivedLength!,
c.deriveParams!,
);
checkDerivedBits(derived);
}
}
/// Check if [privateKey] is sane.
Future<void> checkPrivateKey(PrivateKey? privateKey) async {
check(privateKey != null, 'privateKey is null');
if (r._signBytes != null) {
final sig = await r._signBytes!(