File: Compatibility.java

package info (click to toggle)
openjdk-21 21.0.8%2B9-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 823,976 kB
  • sloc: java: 5,613,338; xml: 1,643,607; cpp: 1,296,296; ansic: 420,291; asm: 404,850; objc: 20,994; sh: 15,271; javascript: 11,245; python: 6,895; makefile: 2,362; perl: 357; awk: 351; sed: 172; jsp: 24; csh: 3
file content (1660 lines) | stat: -rw-r--r-- 67,371 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
/*
 * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/*
 * @test
 * @bug 8217375 8260286 8267319
 * @summary This test is used to verify the compatibility of jarsigner across
 *     different JDK releases. It also can be used to check jar signing (w/
 *     and w/o TSA) and to verify some specific signing and digest algorithms.
 *     Note that this is a manual test. For more details about the test and
 *     its usages, please look through the README.
 *
 * @library /test/lib ../warnings
 * @compile -source 1.8 -target 1.8 JdkUtils.java
 * @run main/manual/othervm Compatibility
 */

import static java.nio.charset.StandardCharsets.UTF_8;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.jar.Attributes.Name;
import java.util.jar.Manifest;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import jdk.test.lib.process.OutputAnalyzer;
import jdk.test.lib.process.ProcessTools;
import jdk.test.lib.util.JarUtils;

public class Compatibility {

    private static final String TEST_SRC = System.getProperty("test.src");
    private static final String TEST_CLASSES = System.getProperty("test.classes");
    private static final String TEST_JDK = System.getProperty("test.jdk");
    private static JdkInfo TEST_JDK_INFO;

    private static final String PROXY_HOST = System.getProperty("proxyHost");
    private static final String PROXY_PORT = System.getProperty("proxyPort", "80");

    // An alternative security properties file.
    // The test provides a default one, which only contains two lines:
    // jdk.certpath.disabledAlgorithms=MD2, MD5
    // jdk.jar.disabledAlgorithms=MD2, MD5
    private static final String JAVA_SECURITY = System.getProperty(
            "javaSecurityFile", TEST_SRC + "/java.security");

    private static final String PASSWORD = "testpass";
    private static final String KEYSTORE = "testKeystore.jks";

    private static final String RSA = "RSA";
    private static final String DSA = "DSA";
    private static final String EC = "EC";
    private static String[] KEY_ALGORITHMS;
    private static final String[] DEFAULT_KEY_ALGORITHMS = new String[] {
            RSA,
            DSA,
            EC};

    private static final String SHA1 = "SHA-1";
    private static final String SHA256 = "SHA-256";
    private static final String SHA384 = "SHA-384";
    private static final String SHA512 = "SHA-512";
    private static final String DEFAULT = "DEFAULT";
    private static String[] DIGEST_ALGORITHMS;
    private static final String[] DEFAULT_DIGEST_ALGORITHMS = new String[] {
            SHA1,
            SHA256,
            SHA384,
            SHA512, // note: digests break onto continuation line in manifest
            DEFAULT};

    private static final boolean[] EXPIRED =
            Boolean.valueOf(System.getProperty("expired", "true")) ?
                    new boolean[] { false, true } : new boolean[] { false };

    private static final boolean TEST_COMPREHENSIVE_JAR_CONTENTS =
            Boolean.valueOf(System.getProperty(
                    "testComprehensiveJarContents", "false"));

    private static final boolean TEST_JAR_UPDATE =
            Boolean.valueOf(System.getProperty("testJarUpdate", "false"));

    private static final boolean STRICT =
            Boolean.valueOf(System.getProperty("strict", "false"));

    private static final Calendar CALENDAR = Calendar.getInstance();
    private static final DateFormat DATE_FORMAT
            = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

    // The certificate validity period in minutes. The default value is 1440
    // minutes, namely 1 day.
    private static final int CERT_VALIDITY
            = Integer.valueOf(System.getProperty("certValidity", "1440"));
    static {
        if (CERT_VALIDITY < 1 || CERT_VALIDITY > 1440) {
            throw new RuntimeException(
                    "certValidity out of range [1, 1440]: " + CERT_VALIDITY);
        }
    }

    // If true, an additional verifying will be triggered after all of
    // valid certificates expire. The default value is false.
    public static final boolean DELAY_VERIFY
            = Boolean.valueOf(System.getProperty("delayVerify", "false"));

    private static long lastCertStartTime;

    private static DetailsOutputStream detailsOutput;

    private static int sigfileCounter;

    private static String nextSigfileName(String alias, String u, String s) {
        String sigfileName = "" + (++sigfileCounter);
        System.out.println("using sigfile " + sigfileName + " for alias "
                    + alias + " signing " + u + ".jar to " + s + ".jar");
        return sigfileName;
    }

    public static void main(String... args) throws Throwable {
        // Backups stdout and stderr.
        PrintStream origStdOut = System.out;
        PrintStream origStdErr = System.err;

        detailsOutput = new DetailsOutputStream(outfile());

        // Redirects the system output to a custom one.
        PrintStream printStream = new PrintStream(detailsOutput);
        System.setOut(printStream);
        System.setErr(printStream);

        TEST_JDK_INFO = new JdkInfo(TEST_JDK);

        List<TsaInfo> tsaList = tsaInfoList();
        List<JdkInfo> jdkInfoList = jdkInfoList();
        List<CertInfo> certList = createCertificates(jdkInfoList);
        List<SignItem> signItems =
                test(jdkInfoList, tsaList, certList, createJars());

        boolean failed = generateReport(jdkInfoList, tsaList, signItems);

        // Restores the original stdout and stderr.
        System.setOut(origStdOut);
        System.setErr(origStdErr);

        if (failed) {
            throw new RuntimeException("At least one test case failed. "
                    + "Please check the failed row(s) in report.html "
                    + "or failedReport.html.");
        }
    }

    private static SignItem createJarFile(String jar, Manifest m,
            String... files) throws IOException {
        JarUtils.createJarFile(Path.of(jar), m, Path.of("."),
                Arrays.stream(files).map(Path::of).toArray(Path[]::new));
        return SignItem.build()
                .signedJar(jar.replaceAll("[.]jar$", ""))
            .addContentFiles(Arrays.stream(files).collect(Collectors.toList()));
    }

    private static String createDummyFile(String name) throws IOException {
        if (name.contains("/")) new File(name).getParentFile().mkdir();
        try (OutputStream fos = new FileOutputStream(name)) {
            fos.write(name.getBytes(UTF_8));
        }
        return name;
    }

    // Creates one or more jar files to test
    private static List<SignItem> createJars() throws IOException {
        List<SignItem> jarList = new ArrayList<>();

        Manifest m = new Manifest();
        m.getMainAttributes().put(Name.MANIFEST_VERSION, "1.0");

        // creates a jar file that contains a dummy file
        jarList.add(createJarFile("test.jar", m, createDummyFile("dummy")));

        if (TEST_COMPREHENSIVE_JAR_CONTENTS) {

            // empty jar file so that jarsigner will add a default manifest
            jarList.add(createJarFile("empty.jar", m));

            // jar file that contains only an empty manifest with empty main
            // attributes (due to missing "Manifest-Version" header)
            JarUtils.createJar("nomainatts.jar");
            jarList.add(SignItem.build().signedJar("nomainatts"));

            // creates a jar file that contains several files.
            jarList.add(createJarFile("files.jar", m,
                    IntStream.range(1, 9).boxed().map(i -> {
                        try {
                            return createDummyFile("dummy" + i);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }).toArray(String[]::new)
            ));

            // forces a line break by exceeding the line width limit of 72 bytes
            // in the filename and hence manifest entry name
            jarList.add(createJarFile("longfilename.jar", m,
                    createDummyFile("test".repeat(20))));

            // another interesting case is with different digest algorithms
            // resulting in digests broken across line breaks onto continuation
            // lines. these however are set with the 'digestAlgs' option or
            // include all digest algorithms by default, see SignTwice.java.
        }

        return jarList;
    }

    // updates a signed jar file by adding another file
    private static List<SignItem> updateJar(SignItem prev) throws IOException {
        List<SignItem> jarList = new ArrayList<>();

        // sign unmodified jar again
        Files.copy(Path.of(prev.signedJar + ".jar"),
                Path.of(prev.signedJar + "-signagainunmodified.jar"));
        jarList.add(SignItem.build(prev)
                .signedJar(prev.signedJar + "-signagainunmodified"));

        String oldJar = prev.signedJar;
        String newJar = oldJar + "-addfile";
        String triggerUpdateFile = "addfile";
        JarUtils.updateJar(oldJar + ".jar", newJar + ".jar", triggerUpdateFile);
        jarList.add(SignItem.build(prev).signedJar(newJar)
                .addContentFiles(Arrays.asList(triggerUpdateFile)));

        return jarList;
    }

    // Creates a key store that includes a set of valid/expired certificates
    // with various algorithms.
    private static List<CertInfo> createCertificates(List<JdkInfo> jdkInfoList)
            throws Throwable {
        List<CertInfo> certList = new ArrayList<>();
        Set<String> expiredCertFilter = new HashSet<>();

        for (JdkInfo jdkInfo : jdkInfoList) {
            for (String keyAlgorithm : keyAlgs()) {
                if (!jdkInfo.supportsKeyAlg(keyAlgorithm)) continue;
                for (int keySize : keySizes(keyAlgorithm)) {
                    for (String digestAlgorithm : digestAlgs()) {
                        for(boolean expired : EXPIRED) {
                            // It creates only one expired certificate for one
                            // key algorithm.
                            if (expired
                                    && !expiredCertFilter.add(keyAlgorithm)) {
                                continue;
                            }

                            CertInfo certInfo = new CertInfo(
                                    jdkInfo,
                                    keyAlgorithm,
                                    digestAlgorithm,
                                    keySize,
                                    expired);
                            // If the signature algorithm is not supported by the
                            // JDK, it cannot try to sign jar with this algorithm.
                            String sigalg = certInfo.sigalg();
                            if (sigalg != null &&
                                    !jdkInfo.isSupportedSigalg(sigalg)) {
                                continue;
                            }
                            createCertificate(jdkInfo, certInfo);
                            certList.add(certInfo);
                        }
                    }
                }
            }
        }

        System.out.println("the keystore contents:");
        for (JdkInfo jdkInfo : jdkInfoList) {
            execTool(jdkInfo.jdkPath + "/bin/keytool", new String[] {
                    "-v",
                    "-storetype",
                    "jks",
                    "-storepass",
                    PASSWORD,
                    "-keystore",
                    KEYSTORE,
                    "-list"
            });
        }

        return certList;
    }

    // Creates/Updates a key store that adds a certificate with specific algorithm.
    private static void createCertificate(JdkInfo jdkInfo, CertInfo certInfo)
            throws Throwable {
        List<String> arguments = new ArrayList<>();
        arguments.add("-J-Djava.security.properties=" + JAVA_SECURITY);
        arguments.add("-v");
        arguments.add("-debug");
        arguments.add("-storetype");
        arguments.add("jks");
        arguments.add("-keystore");
        arguments.add(KEYSTORE);
        arguments.add("-storepass");
        arguments.add(PASSWORD);
        arguments.add(jdkInfo.majorVersion < 6 ? "-genkey" : "-genkeypair");
        arguments.add("-keyalg");
        arguments.add(certInfo.keyAlgorithm);
        String sigalg = certInfo.sigalg();
        if (sigalg != null) {
            arguments.add("-sigalg");
            arguments.add(sigalg);
        }
        if (certInfo.keySize != 0) {
            arguments.add("-keysize");
            arguments.add(certInfo.keySize + "");
        }
        arguments.add("-dname");
        arguments.add("CN=" + certInfo);
        arguments.add("-alias");
        arguments.add(certInfo.alias());
        arguments.add("-keypass");
        arguments.add(PASSWORD);

        arguments.add("-startdate");
        arguments.add(startDate(certInfo.expired));
        arguments.add("-validity");
//        arguments.add(DELAY_VERIFY ? "1" : "222"); // > six months no warn
        arguments.add("1");

        OutputAnalyzer outputAnalyzer = execTool(
                jdkInfo.jdkPath + "/bin/keytool",
                arguments.toArray(new String[arguments.size()]));
        if (outputAnalyzer.getExitValue() != 0
                || outputAnalyzer.getOutput().matches("[Ee]xception")
                || outputAnalyzer.getOutput().matches(Test.ERROR + " ?")) {
            System.out.println(outputAnalyzer.getOutput());
            throw new Exception("error generating a key pair: " + arguments);
        }
    }

    // The validity period of a certificate always be 1 day. For creating an
    // expired certificate, the start date is the time before 1 day, then the
    // certificate expires immediately. And for creating a valid certificate,
    // the start date is the time before (1 day - CERT_VALIDITY minutes), then
    // the certificate will expires in CERT_VALIDITY minutes.
    private static String startDate(boolean expiredCert) {
        CALENDAR.setTime(new Date());
        if (DELAY_VERIFY || expiredCert) {
            // corresponds to '-validity 1'
            CALENDAR.add(Calendar.DAY_OF_MONTH, -1);
        }
        if (DELAY_VERIFY && !expiredCert) {
            CALENDAR.add(Calendar.MINUTE, CERT_VALIDITY);
        }
        Date startDate = CALENDAR.getTime();
        if (!expiredCert) {
            lastCertStartTime = startDate.getTime();
        }
        return DATE_FORMAT.format(startDate);
    }

    private static String outfile() {
        return System.getProperty("o");
    }

    // Retrieves JDK info from the file which is specified by property
    // jdkListFile, or from property jdkList if jdkListFile is not available.
    private static List<JdkInfo> jdkInfoList() throws Throwable {
        String[] jdkList = list("jdkList");
        if (jdkList.length == 0) {
            jdkList = new String[] { "TEST_JDK" };
        }

        List<JdkInfo> jdkInfoList = new ArrayList<>();
        int index = 0;
        for (String jdkPath : jdkList) {
            JdkInfo jdkInfo = "TEST_JDK".equalsIgnoreCase(jdkPath) ?
                    TEST_JDK_INFO : new JdkInfo(jdkPath);
            // The JDK version must be unique.
            if (!jdkInfoList.contains(jdkInfo)) {
                jdkInfo.index = index++;
                jdkInfo.version = String.format(
                        "%s(%d)", jdkInfo.version, jdkInfo.index);
                jdkInfoList.add(jdkInfo);
            } else {
                System.out.println("The JDK version is duplicate: " + jdkPath);
            }
        }
        return jdkInfoList;
    }

    private static List<String> keyAlgs() throws IOException {
        if (KEY_ALGORITHMS == null) KEY_ALGORITHMS = list("keyAlgs");
        if (KEY_ALGORITHMS.length == 0)
            return Arrays.asList(DEFAULT_KEY_ALGORITHMS);
        return Arrays.stream(KEY_ALGORITHMS).map(a -> a.split(";")[0])
                .collect(Collectors.toList());
    }

    // Return key sizes according to the specified key algorithm.
    private static int[] keySizes(String keyAlgorithm) throws IOException {
        if (KEY_ALGORITHMS == null) KEY_ALGORITHMS = list("keyAlgs");
        for (String keyAlg : KEY_ALGORITHMS) {
            String[] split = (keyAlg + " ").split(";");
            if (keyAlgorithm.equals(split[0].trim()) && split.length > 1) {
                int sizes[] = new int[split.length - 1];
                for (int i = 1; i <= sizes.length; i++)
                    sizes[i - 1] = split[i].isBlank() ? 0 : // default
                        Integer.parseInt(split[i].trim());
                return sizes;
            }
        }

        // defaults
        if (RSA.equals(keyAlgorithm) || DSA.equals(keyAlgorithm)) {
            return new int[] { 1024, 2048, 0 }; // 0 is no keysize specified
        } else if (EC.equals(keyAlgorithm)) {
            return new int[] { 384, 521, 0 }; // 0 is no keysize specified
        } else {
            throw new RuntimeException("problem determining key sizes");
        }
    }

    private static List<String> digestAlgs() throws IOException {
        if (DIGEST_ALGORITHMS == null) DIGEST_ALGORITHMS = list("digestAlgs");
        if (DIGEST_ALGORITHMS.length == 0)
            return Arrays.asList(DEFAULT_DIGEST_ALGORITHMS);
        return Arrays.asList(DIGEST_ALGORITHMS);
    }

    // Retrieves TSA info from the file which is specified by property tsaListFile,
    // or from property tsaList if tsaListFile is not available.
    private static List<TsaInfo> tsaInfoList() throws IOException {
        String[] tsaList = list("tsaList");

        List<TsaInfo> tsaInfoList = new ArrayList<>();
        for (int i = 0; i < tsaList.length; i++) {
            String[] values = tsaList[i].split(";digests=");

            String[] digests = new String[0];
            if (values.length == 2) {
                digests = values[1].split(",");
            }

            String tsaUrl = values[0];
            if (tsaUrl.isEmpty() || tsaUrl.equalsIgnoreCase("notsa")) {
                tsaUrl = null;
            }
            TsaInfo bufTsa = new TsaInfo(i, tsaUrl);
            for (String digest : digests) {
                bufTsa.addDigest(digest.toUpperCase());
            }
            tsaInfoList.add(bufTsa);
        }

        if (tsaInfoList.size() == 0) {
            throw new RuntimeException("TSA service is mandatory unless "
                    + "'notsa' specified explicitly.");
        }
        return tsaInfoList;
    }

    private static String[] list(String listProp) throws IOException {
        String listFileProp = listProp + "File";
        String listFile = System.getProperty(listFileProp);
        if (!isEmpty(listFile)) {
            System.out.println(listFileProp + "=" + listFile);
            List<String> list = new ArrayList<>();
            BufferedReader reader = new BufferedReader(
                    new FileReader(listFile));
            String line;
            while ((line = reader.readLine()) != null) {
                String item = line.trim();
                if (!item.isEmpty()) {
                    list.add(item);
                }
            }
            reader.close();
            return list.toArray(new String[list.size()]);
        }

        String list = System.getProperty(listProp);
        System.out.println(listProp + "=" + list);
        return !isEmpty(list) ? list.split("#") : new String[0];
    }

    private static boolean isEmpty(String str) {
        return str == null || str.isEmpty();
    }

    // A JDK (signer) signs a jar with a variety of algorithms, and then all of
    // JDKs (verifiers), including the signer itself, try to verify the signed
    // jars respectively.
    private static List<SignItem> test(List<JdkInfo> jdkInfoList,
            List<TsaInfo> tsaInfoList, List<CertInfo> certList,
            List<SignItem> jars) throws Throwable {
        detailsOutput.transferPhase();
        List<SignItem> signItems = new ArrayList<>();
        signItems.addAll(signing(jdkInfoList, tsaInfoList, certList, jars));
        if (TEST_JAR_UPDATE) {
            signItems.addAll(signing(jdkInfoList, tsaInfoList, certList,
                    updating(signItems.stream().filter(
                            x -> x.status != Status.ERROR)
                    .collect(Collectors.toList()))));
        }

        detailsOutput.transferPhase();
        for (SignItem signItem : signItems) {
            for (JdkInfo verifierInfo : jdkInfoList) {
                if (!verifierInfo.supportsKeyAlg(
                        signItem.certInfo.keyAlgorithm)) continue;
                VerifyItem verifyItem = VerifyItem.build(verifierInfo);
                verifyItem.addSignerCertInfos(signItem);
                signItem.addVerifyItem(verifyItem);
                verifying(signItem, verifyItem);
            }
        }

        // if lastCertExpirationTime passed already now, probably some
        // certificate was already expired during jar signature verification
        // (jarsigner -verify) and the test should probably be repeated with an
        // increased validity period -DcertValidity CERT_VALIDITY
        long lastCertExpirationTime = lastCertStartTime + 24 * 60 * 60 * 1000;
        if (lastCertExpirationTime < System.currentTimeMillis()) {
            throw new AssertionError("CERT_VALIDITY (" + CERT_VALIDITY
                    + " [minutes]) was too short. "
                    + "Creating and signing the jars took longer, "
                    + "presumably at least "
                    + ((lastCertExpirationTime - System.currentTimeMillis())
                            / 60 * 1000 + CERT_VALIDITY) + " [minutes].");
        }

        if (DELAY_VERIFY) {
            detailsOutput.transferPhase();
            System.out.print("Waiting for delay verifying");
            while (System.currentTimeMillis() < lastCertExpirationTime) {
                TimeUnit.SECONDS.sleep(30);
                System.out.print(".");
            }
            System.out.println();

            System.out.println("Delay verifying starts");
            for (SignItem signItem : signItems) {
                for (VerifyItem verifyItem : signItem.verifyItems) {
                    verifying(signItem, verifyItem);
                }
            }
        }

        detailsOutput.transferPhase();
        return signItems;
    }

    private static List<SignItem> signing(List<JdkInfo> jdkInfos,
            List<TsaInfo> tsaList, List<CertInfo> certList,
            List<SignItem> unsignedJars) throws Throwable {
        List<SignItem> signItems = new ArrayList<>();

        for (CertInfo certInfo : certList) {
            JdkInfo signerInfo = certInfo.jdkInfo;
            String keyAlgorithm = certInfo.keyAlgorithm;
            String sigDigestAlgorithm = certInfo.digestAlgorithm;
            int keySize = certInfo.keySize;
            boolean expired = certInfo.expired;

            for (String jarDigestAlgorithm : digestAlgs()) {
                if (DEFAULT.equals(jarDigestAlgorithm)) {
                    jarDigestAlgorithm = null;
                }

                for (TsaInfo tsaInfo : tsaList) {
                    String tsaUrl = tsaInfo.tsaUrl;

                    List<String> tsaDigestAlgs = digestAlgs();
                    // no point in specifying a tsa digest algorithm
                    // for no TSA, except maybe it would issue a warning.
                    if (tsaUrl == null) tsaDigestAlgs = Arrays.asList(DEFAULT);
                    // If the JDK doesn't support option -tsadigestalg, the
                    // associated cases can just be ignored.
                    if (!signerInfo.supportsTsadigestalg) {
                        tsaDigestAlgs = Arrays.asList(DEFAULT);
                    }
                    for (String tsaDigestAlg : tsaDigestAlgs) {
                        if (DEFAULT.equals(tsaDigestAlg)) {
                            tsaDigestAlg = null;
                        } else if (!tsaInfo.isDigestSupported(tsaDigestAlg)) {
                            // It has to ignore the digest algorithm, which
                            // is not supported by the TSA server.
                            continue;
                        }

                        if (tsaUrl != null && TsaFilter.filter(
                                signerInfo.version,
                                tsaDigestAlg,
                                expired,
                                tsaInfo.index)) {
                            continue;
                        }

                        for (SignItem prevSign : unsignedJars) {
                            String unsignedJar = prevSign.signedJar;

                            SignItem signItem = SignItem.build(prevSign)
                                    .certInfo(certInfo)
                                    .jdkInfo(signerInfo);
                            String signedJar = unsignedJar + "-" + "JDK_" + (
                                    signerInfo.version + "-CERT_" + certInfo).
                                    replaceAll("[^a-z_0-9A-Z.]+", "-");

                            if (jarDigestAlgorithm != null) {
                                signedJar += "-DIGESTALG_" + jarDigestAlgorithm;
                                signItem.digestAlgorithm(jarDigestAlgorithm);
                            }
                            if (tsaUrl == null) {
                                signItem.tsaIndex(-1);
                            } else {
                                signedJar += "-TSA_" + tsaInfo.index;
                                signItem.tsaIndex(tsaInfo.index);
                                if (tsaDigestAlg != null) {
                                    signedJar += "-TSADIGALG_" + tsaDigestAlg;
                                    signItem.tsaDigestAlgorithm(tsaDigestAlg);
                                }
                            }
                            signItem.signedJar(signedJar);

                            String signingId = signingId(signItem);
                            detailsOutput.writeAnchorName(signingId,
                                    "Signing: " + signingId);

                            OutputAnalyzer signOA = signJar(
                                    signerInfo.jarsignerPath,
                                    certInfo.sigalg(),
                                    jarDigestAlgorithm,
                                    tsaDigestAlg,
                                    tsaUrl,
                                    certInfo.alias(),
                                    unsignedJar,
                                    signedJar);
                            Status signingStatus = signingStatus(signOA,
                                    tsaUrl != null);
                            signItem.status(signingStatus);
                            signItems.add(signItem);
                        }
                    }
                }
            }
        }

        return signItems;
    }

    private static List<SignItem> updating(List<SignItem> prevSignItems)
            throws IOException {
        List<SignItem> updateItems = new ArrayList<>();
        for (SignItem prevSign : prevSignItems) {
            updateItems.addAll(updateJar(prevSign));
        }
        return updateItems;
    }

    private static void verifying(SignItem signItem, VerifyItem verifyItem)
            throws Throwable {
        // TODO: how will be ensured that the first verification is not after valid period expired which is only one minute?
        boolean delayVerify = verifyItem.status != Status.NONE;
        String verifyingId = verifyingId(signItem, verifyItem, delayVerify);
        detailsOutput.writeAnchorName(verifyingId, "Verifying: " + verifyingId);
        OutputAnalyzer verifyOA = verifyJar(verifyItem.jdkInfo.jarsignerPath,
                signItem.signedJar, verifyItem.certInfo == null ? null :
                verifyItem.certInfo.alias());
        Status verifyingStatus = verifyingStatus(signItem, verifyItem, verifyOA);

        try {
            String match = "^  ("
                    + "  Signature algorithm: " + signItem.certInfo.
                            expectedSigalg(signItem) + ", " + signItem.certInfo.
                            expectedKeySize() + "-bit key"
                    + ")|("
                    + "  Digest algorithm: " + signItem.expectedDigestAlg()
                    + (isWeakAlg(signItem.expectedDigestAlg()) ? " \\(weak\\)" : "")
                    + (signItem.tsaIndex < 0 ? "" :
                      ")|("
                    + "Timestamped by \".+\" on .*"
                    + ")|("
                    + "  Timestamp digest algorithm: "
                            + signItem.expectedTsaDigestAlg()
                    + ")|("
                    + "  Timestamp signature algorithm: .*"
                      )
                    + ")$";
            verifyOA.stdoutShouldMatchByLine(
                    "^- Signed by \"CN=" +  signItem.certInfo.toString()
                            .replaceAll("[.]", "[.]") + "\"$",
                    "^(- Signed by \"CN=.+\")?$",
                    match);
        } catch (Throwable e) {
            e.printStackTrace();
            verifyingStatus = Status.ERROR;
        }

        if (!delayVerify) {
            verifyItem.status(verifyingStatus);
        } else {
            verifyItem.delayStatus(verifyingStatus);
        }

        if (verifyItem.prevVerify != null) {
            verifying(signItem, verifyItem.prevVerify);
        }
    }

    // Determines the status of signing.
    private static Status signingStatus(OutputAnalyzer outputAnalyzer,
            boolean tsa) {
        if (outputAnalyzer.getExitValue() != 0) {
            return Status.ERROR;
        }
        if (!outputAnalyzer.getOutput().contains(Test.JAR_SIGNED)) {
            return Status.ERROR;
        }

        boolean warning = false;
        for (String line : outputAnalyzer.getOutput().lines()
                .toArray(String[]::new)) {
            if (line.matches(Test.ERROR + " ?")) return Status.ERROR;
            if (line.matches(Test.WARNING + " ?")) warning = true;
        }
        return warning ? Status.WARNING : Status.NORMAL;
    }

    // Determines the status of verifying.
    private static Status verifyingStatus(SignItem signItem, VerifyItem
            verifyItem, OutputAnalyzer outputAnalyzer) {
        List<String> expectedSignedContent = new ArrayList<>();
        if (verifyItem.certInfo == null) {
            expectedSignedContent.addAll(signItem.jarContents);
        } else {
            SignItem i = signItem;
            while (i != null) {
                if (i.certInfo != null && i.certInfo.equals(verifyItem.certInfo)) {
                    expectedSignedContent.addAll(i.jarContents);
                }
                i = i.prevSign;
            }
        }
        List<String> expectedUnsignedContent =
                new ArrayList<>(signItem.jarContents);
        expectedUnsignedContent.removeAll(expectedSignedContent);

        int expectedExitCode = !STRICT || expectedUnsignedContent.isEmpty() ? 0 : 32;
        if (outputAnalyzer.getExitValue() != expectedExitCode) {
            System.out.println("verifyingStatus: error: exit code != " + expectedExitCode + ": " + outputAnalyzer.getExitValue() + " != " + expectedExitCode);
            return Status.ERROR;
        }
        String expectedSuccessMessage = expectedUnsignedContent.isEmpty() ?
                Test.JAR_VERIFIED : Test.JAR_VERIFIED_WITH_SIGNER_ERRORS;
        if (!outputAnalyzer.getOutput().contains(expectedSuccessMessage)) {
            System.out.println("verifyingStatus: error: expectedSuccessMessage not found: " + expectedSuccessMessage);
            return Status.ERROR;
        }

        boolean tsa = signItem.tsaIndex >= 0;
        boolean warning = false;
        for (String line : outputAnalyzer.getOutput().lines()
                .toArray(String[]::new)) {
            if (line.isBlank()) {
                // If line is blank and warning flag is true, it is the end of warnings section
                // This is needed when some info is added after warnings, such as timestamp expiration date
                if (warning) warning = false;
                continue;
            }
            if (Test.JAR_VERIFIED.equals(line)) continue;
            if (line.matches(Test.ERROR + " ?") && expectedExitCode == 0) {
                System.out.println("verifyingStatus: error: line.matches(" + Test.ERROR + "\" ?\"): " + line);
                return Status.ERROR;
            }
            if (line.matches(Test.WARNING + " ?")) {
                warning = true;
                continue;
            }
            if (!warning) continue;
            line = line.strip();
            if (Test.NOT_YET_VALID_CERT_SIGNING_WARNING.equals(line)) continue;
            if (Test.HAS_EXPIRING_CERT_SIGNING_WARNING.equals(line)) continue;
            if (Test.HAS_EXPIRING_CERT_VERIFYING_WARNING.equals(line)) continue;
            if (line.matches("^" + Test.NO_TIMESTAMP_SIGNING_WARN_TEMPLATE
                    .replaceAll(
                        "\\(%1\\$tY-%1\\$tm-%1\\$td\\)", "\\\\([^\\\\)]+\\\\)"
                        + "( or after any future revocation date)?")
                    .replaceAll("[.]", "[.]") + "$") && !tsa) continue;
            if (line.matches("^" + Test.NO_TIMESTAMP_VERIFYING_WARN_TEMPLATE
                    .replaceAll("\\(as early as %1\\$tY-%1\\$tm-%1\\$td\\)",
                        "\\\\([^\\\\)]+\\\\)"
                        + "( or after any future revocation date)?")
                    .replaceAll("[.]", "[.]") + "$") && !tsa) continue;
            if (line.matches("^This jar contains signatures that do(es)? not "
                    + "include a timestamp[.] Without a timestamp, users may "
                    + "not be able to validate this jar after the signer "
                    + "certificate's expiration date \\([^\\)]+\\) or after "
                    + "any future revocation date[.]") && !tsa) continue;

            if (isWeakAlg(signItem.expectedDigestAlg())
                    && line.contains(Test.WEAK_ALGORITHM_WARNING)) continue;
            if (line.contains(Test.WEAK_KEY_WARNING)) continue;
            if (Test.CERTIFICATE_SELF_SIGNED.equals(line)) continue;
            if (Test.HAS_EXPIRED_CERT_VERIFYING_WARNING.equals(line)
                    && signItem.certInfo.expired) continue;
            System.out.println("verifyingStatus: unexpected line: " + line);
            return Status.ERROR; // treat unexpected warnings as error
        }
        return warning ? Status.WARNING : Status.NORMAL;
    }

    private static boolean isWeakAlg(String alg) {
        return SHA1.equals(alg);
    }

    // Using specified jarsigner to sign the pre-created jar with specified
    // algorithms.
    private static OutputAnalyzer signJar(String jarsignerPath, String sigalg,
            String jarDigestAlgorithm,
            String tsadigestalg, String tsa, String alias, String unsignedJar,
            String signedJar) throws Throwable {
        List<String> arguments = new ArrayList<>();

        if (PROXY_HOST != null && PROXY_PORT != null) {
            arguments.add("-J-Dhttp.proxyHost=" + PROXY_HOST);
            arguments.add("-J-Dhttp.proxyPort=" + PROXY_PORT);
            arguments.add("-J-Dhttps.proxyHost=" + PROXY_HOST);
            arguments.add("-J-Dhttps.proxyPort=" + PROXY_PORT);
        }
        arguments.add("-J-Djava.security.properties=" + JAVA_SECURITY);
        arguments.add("-debug");
        arguments.add("-verbose");
        if (jarDigestAlgorithm != null) {
            arguments.add("-digestalg");
            arguments.add(jarDigestAlgorithm);
        }
        if (sigalg != null) {
            arguments.add("-sigalg");
            arguments.add(sigalg);
        }
        if (tsa != null) {
            arguments.add("-tsa");
            arguments.add(tsa);
        }
        if (tsadigestalg != null) {
            arguments.add("-tsadigestalg");
            arguments.add(tsadigestalg);
        }
        arguments.add("-keystore");
        arguments.add(KEYSTORE);
        arguments.add("-storepass");
        arguments.add(PASSWORD);
        arguments.add("-sigfile");
        arguments.add(nextSigfileName(alias, unsignedJar, signedJar));
        arguments.add("-signedjar");
        arguments.add(signedJar + ".jar");
        arguments.add(unsignedJar + ".jar");
        arguments.add(alias);

        OutputAnalyzer outputAnalyzer = execTool(jarsignerPath,
                arguments.toArray(new String[arguments.size()]));
        return outputAnalyzer;
    }

    // Using specified jarsigner to verify the signed jar.
    private static OutputAnalyzer verifyJar(String jarsignerPath,
            String signedJar, String alias) throws Throwable {
        List<String> arguments = new ArrayList<>();
        arguments.add("-J-Djava.security.properties=" + JAVA_SECURITY);
        arguments.add("-debug");
        arguments.add("-verbose");
        arguments.add("-certs");
        arguments.add("-keystore");
        arguments.add(KEYSTORE);
        arguments.add("-verify");
        if (STRICT) arguments.add("-strict");
        arguments.add(signedJar + ".jar");
        if (alias != null) arguments.add(alias);
        OutputAnalyzer outputAnalyzer = execTool(jarsignerPath,
                arguments.toArray(new String[arguments.size()]));
        return outputAnalyzer;
    }

    // Generates the test result report.
    private static boolean generateReport(List<JdkInfo> jdkList, List<TsaInfo> tsaList,
            List<SignItem> signItems) throws IOException {
        System.out.println("Report is being generated...");

        StringBuilder report = new StringBuilder();
        report.append(HtmlHelper.startHtml());
        report.append(HtmlHelper.startPre());

        // Generates JDK list
        report.append("JDK list:\n");
        for(JdkInfo jdkInfo : jdkList) {
            report.append(String.format("%d=%s%n",
                    jdkInfo.index,
                    jdkInfo.runtimeVersion));
        }

        // Generates TSA URLs
        report.append("TSA list:\n");
        for(TsaInfo tsaInfo : tsaList) {
            report.append(
                    String.format("%d=%s%n", tsaInfo.index,
                            tsaInfo.tsaUrl == null ? "notsa" : tsaInfo.tsaUrl));
        }
        report.append(HtmlHelper.endPre());

        report.append(HtmlHelper.startTable());
        // Generates report headers.
        List<String> headers = new ArrayList<>();
        headers.add("[Jarfile]");
        headers.add("[Signing Certificate]");
        headers.add("[Signer JDK]");
        headers.add("[Signature Algorithm]");
        headers.add("[Jar Digest Algorithm]");
        headers.add("[TSA Digest Algorithm]");
        headers.add("[TSA]");
        headers.add("[Signing Status]");
        headers.add("[Verifier JDK]");
        headers.add("[Verifying Certificate]");
        headers.add("[Verifying Status]");
        if (DELAY_VERIFY) {
            headers.add("[Delay Verifying Status]");
        }
        headers.add("[Failed]");
        report.append(HtmlHelper.htmlRow(
                headers.toArray(new String[headers.size()])));

        StringBuilder failedReport = new StringBuilder(report.toString());

        boolean failed = signItems.isEmpty();

        // Generates report rows.
        for (SignItem signItem : signItems) {
            failed = failed || signItem.verifyItems.isEmpty();
            for (VerifyItem verifyItem : signItem.verifyItems) {
                String reportRow = reportRow(signItem, verifyItem);
                report.append(reportRow);
                boolean isFailedCase = isFailed(signItem, verifyItem);
                if (isFailedCase) {
                    failedReport.append(reportRow);
                }
                failed = failed || isFailedCase;
            }
        }

        report.append(HtmlHelper.endTable());
        report.append(HtmlHelper.endHtml());
        generateFile("report.html", report.toString());
        if (failed) {
            failedReport.append(HtmlHelper.endTable());
            failedReport.append(HtmlHelper.endPre());
            failedReport.append(HtmlHelper.endHtml());
            generateFile("failedReport.html", failedReport.toString());
        }

        System.out.println("Report is generated.");
        return failed;
    }

    private static void generateFile(String path, String content)
            throws IOException {
        FileWriter writer = new FileWriter(new File(path));
        writer.write(content);
        writer.close();
    }

    private static String jarsignerPath(String jdkPath) {
        return jdkPath + "/bin/jarsigner";
    }

    // Executes the specified function on JdkUtils by the specified JDK.
    private static String execJdkUtils(String jdkPath, String method,
            String... args) throws Throwable {
        String[] cmd = new String[args.length + 5];
        cmd[0] = jdkPath + "/bin/java";
        cmd[1] = "-cp";
        cmd[2] = TEST_CLASSES;
        cmd[3] = JdkUtils.class.getName();
        cmd[4] = method;
        System.arraycopy(args, 0, cmd, 5, args.length);
        return ProcessTools.executeCommand(cmd).getStdout();
    }

    // Executes the specified JDK tools, such as keytool and jarsigner, and
    // ensures the output is in US English.
    private static OutputAnalyzer execTool(String toolPath, String... args)
            throws Throwable {
        long start = System.currentTimeMillis();
        try {
            String[] cmd;

            cmd = new String[args.length + 3];
            System.arraycopy(args, 0, cmd, 3, args.length);
            cmd[0] = toolPath;
            cmd[1] = "-J-Duser.language=en";
            cmd[2] = "-J-Duser.country=US";
            return ProcessTools.executeCommand(cmd);

        } finally {
            long end = System.currentTimeMillis();
            System.out.println("child process duration [ms]: " + (end - start));
        }
    }

    private static class JdkInfo {

        private int index;
        private final String jdkPath;
        private final String jarsignerPath;
        private final String runtimeVersion;
        private String version;
        private final int majorVersion;
        private final boolean supportsTsadigestalg;

        private Map<String, Boolean> sigalgMap = new HashMap<>();

        private JdkInfo(String jdkPath) throws Throwable {
            this.jdkPath = jdkPath;
            jarsignerPath = jarsignerPath(jdkPath);
            runtimeVersion = execJdkUtils(jdkPath, JdkUtils.M_JAVA_RUNTIME_VERSION);
            if (runtimeVersion == null || runtimeVersion.isBlank()) {
                throw new RuntimeException(
                        "Cannot determine the JDK version: " + jdkPath);
            }
            version = execJdkUtils(jdkPath, JdkUtils.M_JAVA_VERSION);
            majorVersion = Integer.parseInt((runtimeVersion.matches("^1[.].*") ?
                    runtimeVersion.substring(2) : runtimeVersion).replaceAll("[^0-9].*$", ""));
            supportsTsadigestalg = execTool(jarsignerPath, "-help")
                    .getOutput().contains("-tsadigestalg");
        }

        private boolean isSupportedSigalg(String sigalg) throws Throwable {
            if (!sigalgMap.containsKey(sigalg)) {
                boolean isSupported = Boolean.parseBoolean(
                        execJdkUtils(
                                jdkPath,
                                JdkUtils.M_IS_SUPPORTED_SIGALG,
                                sigalg));
                sigalgMap.put(sigalg, isSupported);
            }

            return sigalgMap.get(sigalg);
        }

        private boolean isAtLeastMajorVersion(int minVersion) {
            return majorVersion >= minVersion;
        }

        private boolean supportsKeyAlg(String keyAlgorithm) {
            // JDK 6 doesn't support EC
            return isAtLeastMajorVersion(6) || !EC.equals(keyAlgorithm);
        }

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result
                    + ((runtimeVersion == null) ? 0 : runtimeVersion.hashCode());
            return result;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            JdkInfo other = (JdkInfo) obj;
            if (runtimeVersion == null) {
                if (other.runtimeVersion != null)
                    return false;
            } else if (!runtimeVersion.equals(other.runtimeVersion))
                return false;
            return true;
        }

        @Override
        public String toString() {
            return "JdkInfo[" + runtimeVersion + ", " + jdkPath + "]";
        }
    }

    private static class TsaInfo {

        private final int index;
        private final String tsaUrl;
        private Set<String> digestList = new HashSet<>();

        private TsaInfo(int index, String tsa) {
            this.index = index;
            this.tsaUrl = tsa;
        }

        private void addDigest(String digest) {
            digestList.add(digest);
        }

        private boolean isDigestSupported(String digest) {
            return digest == null || digestList.isEmpty()
                    || digestList.contains(digest);
        }

        @Override
        public String toString() {
            return "TsaInfo[" + index + ", " + tsaUrl + "]";
        }
    }

    private static class CertInfo {

        private static int certCounter;

        // nr distinguishes cert CNs in jarsigner -verify output
        private final int nr = ++certCounter;
        private final JdkInfo jdkInfo;
        private final String keyAlgorithm;
        private final String digestAlgorithm;
        private final int keySize;
        private final boolean expired;

        private CertInfo(JdkInfo jdkInfo, String keyAlgorithm,
                String digestAlgorithm, int keySize, boolean expired) {
            this.jdkInfo = jdkInfo;
            this.keyAlgorithm = keyAlgorithm;
            this.digestAlgorithm = digestAlgorithm;
            this.keySize = keySize;
            this.expired = expired;
        }

        private String sigalg() {
            return DEFAULT.equals(digestAlgorithm) ? null : expectedSigalg();
        }

        private String expectedSigalg() {
            return "SHA256with" + keyAlgorithm + (EC.equals(keyAlgorithm) ? "DSA" : "");
        }

        private String expectedSigalg(SignItem signer) {
            if (!DEFAULT.equals(digestAlgorithm)) {
                return "SHA256with" + keyAlgorithm + (EC.equals(keyAlgorithm) ? "DSA" : "");

            } else {
                // default algorithms documented for jarsigner here:
                // https://docs.oracle.com/en/java/javase/17/docs/specs/man/jarsigner.html#supported-algorithms
                // https://docs.oracle.com/en/java/javase/20/docs/specs/man/jarsigner.html#supported-algorithms
                int expectedKeySize = expectedKeySize();
                switch (keyAlgorithm) {
                    case DSA:
                        return "SHA256withDSA";
                    case RSA: {
                        if ((signer.jdkInfo.majorVersion >= 20 && expectedKeySize < 624)
                                || (signer.jdkInfo.majorVersion < 20 && expectedKeySize <= 3072)) {
                            return "SHA256withRSA";
                        } else if (expectedKeySize <= 7680) {
                            return "SHA384withRSA";
                        } else {
                            return "SHA512withRSA";
                        }
                    }
                    case EC: {
                        if (signer.jdkInfo.majorVersion < 20 && expectedKeySize < 384) {
                            return "SHA256withECDSA";
                        } else if (expectedKeySize < 512) {
                            return "SHA384withECDSA";
                        } else {
                            return "SHA512withECDSA";
                        }
                    }
                    default:
                        throw new RuntimeException("Unsupported/expected key algorithm: " + keyAlgorithm);
                }
            }
        }

        private int expectedKeySize() {
            if (keySize != 0) return keySize;

            // defaults
            if (RSA.equals(keyAlgorithm)) {
                return jdkInfo.majorVersion >= 20 ? 3072 : 2048;
            } else if (DSA.equals(keyAlgorithm)) {
                return 2048;
            } else if (EC.equals(keyAlgorithm)) {
                return jdkInfo.majorVersion >= 20 ? 384 : 256;
            } else {
                throw new RuntimeException("problem determining key size");
            }
        }

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result
                    + (digestAlgorithm == null ? 0 : digestAlgorithm.hashCode());
            result = prime * result + (expired ? 1231 : 1237);
            result = prime * result
                    + (jdkInfo == null ? 0 : jdkInfo.hashCode());
            result = prime * result
                    + (keyAlgorithm == null ? 0 : keyAlgorithm.hashCode());
            result = prime * result + keySize;
            return result;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            CertInfo other = (CertInfo) obj;
            if (digestAlgorithm == null) {
                if (other.digestAlgorithm != null)
                    return false;
            } else if (!digestAlgorithm.equals(other.digestAlgorithm))
                return false;
            if (expired != other.expired)
                return false;
            if (jdkInfo == null) {
                if (other.jdkInfo != null)
                    return false;
            } else if (!jdkInfo.equals(other.jdkInfo))
                return false;
            if (keyAlgorithm == null) {
                if (other.keyAlgorithm != null)
                    return false;
            } else if (!keyAlgorithm.equals(other.keyAlgorithm))
                return false;
            if (keySize != other.keySize)
                return false;
            return true;
        }

        private String alias() {
            return (jdkInfo.version + "_" + toString())
                    // lower case for jks due to
                    // sun.security.provider.JavaKeyStore.JDK.convertAlias
                    .toLowerCase(Locale.ENGLISH);
        }

        @Override
        public String toString() {
            return "nr" + nr + "_"
                    + keyAlgorithm + "_" + digestAlgorithm
                    + (keySize == 0 ? "" : "_" + keySize)
                    + (expired ? "_Expired" : "");
        }
    }

    // It does only one timestamping for the same JDK, digest algorithm and
    // TSA service with an arbitrary valid/expired certificate.
    private static class TsaFilter {

        private static final Set<Condition> SET = new HashSet<>();

        private static boolean filter(String signerVersion,
                String digestAlgorithm, boolean expiredCert, int tsaIndex) {
            return !SET.add(new Condition(signerVersion, digestAlgorithm,
                    expiredCert, tsaIndex));
        }

        private static class Condition {

            private final String signerVersion;
            private final String digestAlgorithm;
            private final boolean expiredCert;
            private final int tsaIndex;

            private Condition(String signerVersion, String digestAlgorithm,
                    boolean expiredCert, int tsaIndex) {
                this.signerVersion = signerVersion;
                this.digestAlgorithm = digestAlgorithm;
                this.expiredCert = expiredCert;
                this.tsaIndex = tsaIndex;
            }

            @Override
            public int hashCode() {
                final int prime = 31;
                int result = 1;
                result = prime * result
                        + ((digestAlgorithm == null) ? 0 : digestAlgorithm.hashCode());
                result = prime * result + (expiredCert ? 1231 : 1237);
                result = prime * result
                        + ((signerVersion == null) ? 0 : signerVersion.hashCode());
                result = prime * result + tsaIndex;
                return result;
            }

            @Override
            public boolean equals(Object obj) {
                if (this == obj)
                    return true;
                if (obj == null)
                    return false;
                if (getClass() != obj.getClass())
                    return false;
                Condition other = (Condition) obj;
                if (digestAlgorithm == null) {
                    if (other.digestAlgorithm != null)
                        return false;
                } else if (!digestAlgorithm.equals(other.digestAlgorithm))
                    return false;
                if (expiredCert != other.expiredCert)
                    return false;
                if (signerVersion == null) {
                    if (other.signerVersion != null)
                        return false;
                } else if (!signerVersion.equals(other.signerVersion))
                    return false;
                if (tsaIndex != other.tsaIndex)
                    return false;
                return true;
            }
        }}

    private static enum Status {

        // No action due to pre-action fails.
        NONE,

        // jar is signed/verified with error
        ERROR,

        // jar is signed/verified with warning
        WARNING,

        // jar is signed/verified without any warning and error
        NORMAL
    }

    private static class SignItem {

        private SignItem prevSign;
        private CertInfo certInfo;
        private JdkInfo jdkInfo;
        private String digestAlgorithm;
        private String tsaDigestAlgorithm;
        private int tsaIndex;
        private Status status;
        private String unsignedJar;
        private String signedJar;
        private List<String> jarContents = new ArrayList<>();

        private List<VerifyItem> verifyItems = new ArrayList<>();

        private static SignItem build() {
            return new SignItem()
                    .addContentFiles(Arrays.asList("META-INF/MANIFEST.MF"));
        }

        private static SignItem build(SignItem prevSign) {
            return build().prevSign(prevSign).unsignedJar(prevSign.signedJar)
                    .addContentFiles(prevSign.jarContents);
        }

        private SignItem prevSign(SignItem prevSign) {
            this.prevSign = prevSign;
            return this;
        }

        private SignItem certInfo(CertInfo certInfo) {
            this.certInfo = certInfo;
            return this;
        }

        private SignItem jdkInfo(JdkInfo jdkInfo) {
            this.jdkInfo = jdkInfo;
            return this;
        }

        private SignItem digestAlgorithm(String digestAlgorithm) {
            this.digestAlgorithm = digestAlgorithm;
            return this;
        }

        String expectedDigestAlg() {
            return digestAlgorithm != null
                    ? digestAlgorithm
                    : jdkInfo.majorVersion >= 20 ? "SHA-384" : "SHA-256";
        }

        private SignItem tsaDigestAlgorithm(String tsaDigestAlgorithm) {
            this.tsaDigestAlgorithm = tsaDigestAlgorithm;
            return this;
        }

        String expectedTsaDigestAlg() {
            return tsaDigestAlgorithm != null ? tsaDigestAlgorithm : "SHA-256";
        }

        private SignItem tsaIndex(int tsaIndex) {
            this.tsaIndex = tsaIndex;
            return this;
        }

        private SignItem status(Status status) {
            this.status = status;
            return this;
        }

        private SignItem unsignedJar(String unsignedJar) {
            this.unsignedJar = unsignedJar;
            return this;
        }

        private SignItem signedJar(String signedJar) {
            this.signedJar = signedJar;
            return this;
        }

        private SignItem addContentFiles(List<String> files) {
            this.jarContents.addAll(files);
            return this;
        }

        private void addVerifyItem(VerifyItem verifyItem) {
            verifyItems.add(verifyItem);
        }

        private boolean isErrorInclPrev() {
            if (prevSign != null && prevSign.isErrorInclPrev()) {
                System.out.println("SignItem.isErrorInclPrev: returning true from previous");
                return true;
            }

            return status == Status.ERROR;
        }
        private List<String> toStringWithPrev(Function<SignItem,String> toStr) {
            List<String> s = new ArrayList<>();
            if (prevSign != null) {
                s.addAll(prevSign.toStringWithPrev(toStr));
            }
            if (status != null) { // no status means jar creation or update item
                s.add(toStr.apply(this));
            }
            return s;
        }
    }

    private static class VerifyItem {

        private VerifyItem prevVerify;
        private CertInfo certInfo;
        private JdkInfo jdkInfo;
        private Status status = Status.NONE;
        private Status delayStatus = Status.NONE;

        private static VerifyItem build(JdkInfo jdkInfo) {
            VerifyItem verifyItem = new VerifyItem();
            verifyItem.jdkInfo = jdkInfo;
            return verifyItem;
        }

        private VerifyItem certInfo(CertInfo certInfo) {
            this.certInfo = certInfo;
            return this;
        }

        private void addSignerCertInfos(SignItem signItem) {
            VerifyItem prevVerify = this;
            CertInfo lastCertInfo = null;
            while (signItem != null) {
                // (signItem.certInfo == null) means create or update jar step
                if (signItem.certInfo != null
                        && !signItem.certInfo.equals(lastCertInfo)) {
                    lastCertInfo = signItem.certInfo;
                    prevVerify = prevVerify.prevVerify =
                            build(jdkInfo).certInfo(signItem.certInfo);
                }
                signItem = signItem.prevSign;
            }
        }

        private VerifyItem status(Status status) {
            this.status = status;
            return this;
        }

        private boolean isErrorInclPrev() {
            if (prevVerify != null && prevVerify.isErrorInclPrev()) {
                System.out.println("VerifyItem.isErrorInclPrev: returning true from previous");
                return true;
            }

            return status == Status.ERROR || delayStatus == Status.ERROR;
        }

        private VerifyItem delayStatus(Status status) {
            this.delayStatus = status;
            return this;
        }

        private List<String> toStringWithPrev(
                Function<VerifyItem,String> toStr) {
            List<String> s = new ArrayList<>();
            if (prevVerify != null) {
                s.addAll(prevVerify.toStringWithPrev(toStr));
            }
            s.add(toStr.apply(this));
            return s;
        }
    }

    // The identifier for a specific signing.
    private static String signingId(SignItem signItem) {
        return signItem.signedJar;
    }

    // The identifier for a specific verifying.
    private static String verifyingId(SignItem signItem, VerifyItem verifyItem,
            boolean delayVerify) {
        return signingId(signItem) + (delayVerify ? "-DV" : "-V")
                + "_" + verifyItem.jdkInfo.version +
                (verifyItem.certInfo == null ? "" : "_" + verifyItem.certInfo);
    }

    private static String reportRow(SignItem signItem, VerifyItem verifyItem) {
        List<String> values = new ArrayList<>();
        Consumer<Function<SignItem, String>> s_values_add = f -> {
            values.add(String.join("<br/><br/>", signItem.toStringWithPrev(f)));
        };
        Consumer<Function<VerifyItem, String>> v_values_add = f -> {
            values.add(String.join("<br/><br/>", verifyItem.toStringWithPrev(f)));
        };
        s_values_add.accept(i -> i.unsignedJar + " -> " + i.signedJar);
        s_values_add.accept(i -> i.certInfo.toString());
        s_values_add.accept(i -> i.jdkInfo.version);
        s_values_add.accept(i -> i.certInfo.expectedSigalg(i));
        s_values_add.accept(i ->
                null2Default(i.digestAlgorithm, i.expectedDigestAlg()));
        s_values_add.accept(i -> i.tsaIndex == -1 ? "" :
                null2Default(i.tsaDigestAlgorithm, i.expectedTsaDigestAlg()));
        s_values_add.accept(i -> i.tsaIndex == -1 ? "" : i.tsaIndex + "");
        s_values_add.accept(i -> HtmlHelper.anchorLink(
                PhaseOutputStream.fileName(PhaseOutputStream.Phase.SIGNING),
                signingId(i),
                "" + i.status));
        values.add(verifyItem.jdkInfo.version);
        v_values_add.accept(i ->
                i.certInfo == null ? "no alias" : "" + i.certInfo);
        v_values_add.accept(i -> HtmlHelper.anchorLink(
                PhaseOutputStream.fileName(PhaseOutputStream.Phase.VERIFYING),
                verifyingId(signItem, i, false),
                "" + i.status.toString()));
        if (DELAY_VERIFY) {
            v_values_add.accept(i -> HtmlHelper.anchorLink(
                    PhaseOutputStream.fileName(
                            PhaseOutputStream.Phase.DELAY_VERIFYING),
                    verifyingId(signItem, verifyItem, true),
                    verifyItem.delayStatus.toString()));
        }
        values.add(isFailed(signItem, verifyItem) ? "X" : "");
        return HtmlHelper.htmlRow(values.toArray(new String[values.size()]));
    }

    private static boolean isFailed(SignItem signItem, VerifyItem verifyItem) {
        System.out.println("isFailed: signItem = " + signItem + ", verifyItem = " + verifyItem);
        // TODO: except known failing cases

        // Note about isAtLeastMajorVersion in the following conditions:
        // signItem.jdkInfo is the jdk which signed the jar last and
        // signItem.prevSign.jdkInfo is the jdk which signed the jar first
        // assuming only two successive signatures as there actually are now.
        // the first signature always works and always has. subject here is
        // the update of an already signed jar. the following conditions always
        // depend on the second jdk that updated the jar with another signature
        // and the first one (signItem(.prevSign)+.jdkInfo) can be ignored.
        // this is different for verifyItem. verifyItem.prevVerify refers to
        // the first signature created by signItem(.prevSign)+.jdkInfo.
        // all verifyItem(.prevVerify)+.jdkInfo however point always to the same
        // jdk, only their certInfo is different. the same signatures are
        // verified with different jdks in different top-level VerifyItems
        // attached directly to signItem.verifyItems and not to
        // verifyItem.prevVerify.

        // ManifestDigester fails to parse manifests ending in '\r' with
        // IndexOutOfBoundsException at ManifestDigester.java:87 before 8217375
        if (signItem.signedJar.startsWith("eofr")
                && !signItem.jdkInfo.isAtLeastMajorVersion(13)
                && !verifyItem.jdkInfo.isAtLeastMajorVersion(13)) return false;

        // if there is no blank line after main attributes, JarSigner adds
        // individual sections nevertheless without being properly delimited
        // in JarSigner.java:777..790 without checking for blank line
        // before 8217375
//        if (signItem.signedJar.startsWith("eofn-")
//                && signItem.signedJar.contains("-addfile-")
//                && !signItem.jdkInfo.isAtLeastMajorVersion(13)
//                && !verifyItem.jdkInfo.isAtLeastMajorVersion(13)) return false; // FIXME

//        System.out.println("isFailed: signItem.isErrorInclPrev() " + signItem.isErrorInclPrev());
//        System.out.println("isFailed: verifyItem.isErrorInclPrev() " + verifyItem.isErrorInclPrev());
        boolean isFailed = signItem.isErrorInclPrev() || verifyItem.isErrorInclPrev();
        System.out.println("isFailed: returning " + isFailed);
        return isFailed;
    }

    // If a value is null, then displays the default value or N/A.
    private static String null2Default(String value, String defaultValue) {
        return value != null ? value :
               DEFAULT + "(" + (defaultValue == null
                                  ? "N/A"
                                  : defaultValue) + ")";
    }

}