Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/test/jdk/sun/security/pkcs11/PKCS11Test.java
41152 views
1
/*
2
* Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation.
8
*
9
* This code is distributed in the hope that it will be useful, but WITHOUT
10
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12
* version 2 for more details (a copy is included in the LICENSE file that
13
* accompanied this code).
14
*
15
* You should have received a copy of the GNU General Public License version
16
* 2 along with this work; if not, write to the Free Software Foundation,
17
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18
*
19
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20
* or visit www.oracle.com if you need additional information or have any
21
* questions.
22
*/
23
24
// common infrastructure for SunPKCS11 tests
25
26
import java.io.ByteArrayOutputStream;
27
import java.io.File;
28
import java.io.IOException;
29
import java.io.InputStream;
30
import java.io.StringReader;
31
import java.nio.charset.StandardCharsets;
32
import java.nio.file.Files;
33
import java.nio.file.Path;
34
import java.nio.file.Paths;
35
import java.nio.file.StandardCopyOption;
36
import java.security.AlgorithmParameters;
37
import java.security.InvalidAlgorithmParameterException;
38
import java.security.KeyPairGenerator;
39
import java.security.NoSuchProviderException;
40
import java.security.Policy;
41
import java.security.Provider;
42
import java.security.ProviderException;
43
import java.security.Security;
44
import java.security.spec.ECGenParameterSpec;
45
import java.security.spec.ECParameterSpec;
46
import java.util.ArrayList;
47
import java.util.Arrays;
48
import java.util.HashMap;
49
import java.util.Iterator;
50
import java.util.List;
51
import java.util.Map;
52
import java.util.Optional;
53
import java.util.Properties;
54
import java.util.ServiceConfigurationError;
55
import java.util.ServiceLoader;
56
import java.util.Set;
57
58
import jdk.test.lib.artifacts.Artifact;
59
import jdk.test.lib.artifacts.ArtifactResolver;
60
import jdk.test.lib.artifacts.ArtifactResolverException;
61
62
public abstract class PKCS11Test {
63
64
private boolean enableSM = false;
65
66
static final Properties props = System.getProperties();
67
68
static final String PKCS11 = "PKCS11";
69
70
// directory of the test source
71
static final String BASE = System.getProperty("test.src", ".");
72
73
static final String TEST_CLASSES = System.getProperty("test.classes", ".");
74
75
static final char SEP = File.separatorChar;
76
77
private static final String DEFAULT_POLICY =
78
BASE + SEP + ".." + SEP + "policy";
79
80
// directory corresponding to BASE in the /closed hierarchy
81
static final String CLOSED_BASE;
82
83
static {
84
// hack
85
String absBase = new File(BASE).getAbsolutePath();
86
int k = absBase.indexOf(SEP + "test" + SEP + "jdk" + SEP);
87
if (k < 0) k = 0;
88
String p1 = absBase.substring(0, k);
89
String p2 = absBase.substring(k);
90
CLOSED_BASE = p1 + "/../closed" + p2;
91
92
// set it as a system property to make it available in policy file
93
System.setProperty("closed.base", CLOSED_BASE);
94
}
95
96
// NSS version info
97
public static enum ECCState { None, Basic, Extended };
98
static double nss_version = -1;
99
static ECCState nss_ecc_status = ECCState.Basic;
100
101
// The NSS library we need to search for in getNSSLibDir()
102
// Default is "libsoftokn3.so", listed as "softokn3"
103
// The other is "libnss3.so", listed as "nss3".
104
static String nss_library = "softokn3";
105
106
// NSS versions of each library. It is simplier to keep nss_version
107
// for quick checking for generic testing than many if-else statements.
108
static double softoken3_version = -1;
109
static double nss3_version = -1;
110
static Provider pkcs11 = newPKCS11Provider();
111
112
public static Provider newPKCS11Provider() {
113
ServiceLoader sl = ServiceLoader.load(java.security.Provider.class);
114
Iterator<Provider> iter = sl.iterator();
115
Provider p = null;
116
boolean found = false;
117
while (iter.hasNext()) {
118
try {
119
p = iter.next();
120
if (p.getName().equals("SunPKCS11")) {
121
found = true;
122
break;
123
}
124
} catch (Exception | ServiceConfigurationError e) {
125
// ignore and move on to the next one
126
}
127
}
128
// Nothing found through ServiceLoader; fall back to reflection
129
if (!found) {
130
try {
131
Class clazz = Class.forName("sun.security.pkcs11.SunPKCS11");
132
p = (Provider) clazz.newInstance();
133
} catch (Exception ex) {
134
ex.printStackTrace();
135
}
136
}
137
return p;
138
}
139
140
// Return the static test SunPKCS11 provider configured with the specified config file
141
static Provider getSunPKCS11(String config) throws Exception {
142
return getSunPKCS11(config, pkcs11);
143
}
144
145
// Return the Provider p configured with the specified config file
146
static Provider getSunPKCS11(String config, Provider p) throws Exception {
147
if (p == null) {
148
throw new NoSuchProviderException("No PKCS11 provider available");
149
}
150
return p.configure(config);
151
}
152
153
public abstract void main(Provider p) throws Exception;
154
155
protected boolean skipTest(Provider p) {
156
return false;
157
}
158
159
private void premain(Provider p) throws Exception {
160
if (skipTest(p)) {
161
return;
162
}
163
164
// set a security manager and policy before a test case runs,
165
// and disable them after the test case finished
166
try {
167
if (enableSM) {
168
System.setSecurityManager(new SecurityManager());
169
}
170
long start = System.currentTimeMillis();
171
System.out.printf(
172
"Running test with provider %s (security manager %s) ...%n",
173
p.getName(), enableSM ? "enabled" : "disabled");
174
main(p);
175
long stop = System.currentTimeMillis();
176
System.out.println("Completed test with provider " + p.getName() +
177
" (" + (stop - start) + " ms).");
178
} finally {
179
if (enableSM) {
180
System.setSecurityManager(null);
181
}
182
}
183
}
184
185
public static void main(PKCS11Test test) throws Exception {
186
main(test, null);
187
}
188
189
public static void main(PKCS11Test test, String[] args) throws Exception {
190
if (args != null) {
191
if (args.length > 0) {
192
if ("sm".equals(args[0])) {
193
test.enableSM = true;
194
} else {
195
throw new RuntimeException("Unknown Command, use 'sm' as "
196
+ "first argument to enable security manager");
197
}
198
}
199
if (test.enableSM) {
200
System.setProperty("java.security.policy",
201
(args.length > 1) ? BASE + SEP + args[1]
202
: DEFAULT_POLICY);
203
}
204
}
205
206
Provider[] oldProviders = Security.getProviders();
207
try {
208
System.out.println("Beginning test run " + test.getClass().getName() + "...");
209
testDefault(test);
210
testNSS(test);
211
testDeimos(test);
212
} finally {
213
// NOTE: Do not place a 'return' in any finally block
214
// as it will suppress exceptions and hide test failures.
215
Provider[] newProviders = Security.getProviders();
216
boolean found = true;
217
// Do not restore providers if nothing changed. This is especailly
218
// useful for ./Provider/Login.sh, where a SecurityManager exists.
219
if (oldProviders.length == newProviders.length) {
220
found = false;
221
for (int i = 0; i<oldProviders.length; i++) {
222
if (oldProviders[i] != newProviders[i]) {
223
found = true;
224
break;
225
}
226
}
227
}
228
if (found) {
229
for (Provider p: newProviders) {
230
Security.removeProvider(p.getName());
231
}
232
for (Provider p: oldProviders) {
233
Security.addProvider(p);
234
}
235
}
236
}
237
}
238
239
public static void testDeimos(PKCS11Test test) throws Exception {
240
if (new File("/opt/SUNWconn/lib/libpkcs11.so").isFile() == false ||
241
"true".equals(System.getProperty("NO_DEIMOS"))) {
242
return;
243
}
244
String base = getBase();
245
String p11config = base + SEP + "nss" + SEP + "p11-deimos.txt";
246
Provider p = getSunPKCS11(p11config);
247
test.premain(p);
248
}
249
250
public static void testDefault(PKCS11Test test) throws Exception {
251
// run test for default configured PKCS11 providers (if any)
252
253
if ("true".equals(System.getProperty("NO_DEFAULT"))) {
254
return;
255
}
256
257
Provider[] providers = Security.getProviders();
258
for (int i = 0; i < providers.length; i++) {
259
Provider p = providers[i];
260
if (p.getName().startsWith("SunPKCS11-")) {
261
test.premain(p);
262
}
263
}
264
}
265
266
private static String PKCS11_BASE;
267
static {
268
try {
269
PKCS11_BASE = getBase();
270
} catch (Exception e) {
271
// ignore
272
}
273
}
274
275
private final static String PKCS11_REL_PATH = "sun/security/pkcs11";
276
277
public static String getBase() throws Exception {
278
if (PKCS11_BASE != null) {
279
return PKCS11_BASE;
280
}
281
File cwd = new File(System.getProperty("test.src", ".")).getCanonicalFile();
282
while (true) {
283
File file = new File(cwd, "TEST.ROOT");
284
if (file.isFile()) {
285
break;
286
}
287
cwd = cwd.getParentFile();
288
if (cwd == null) {
289
throw new Exception("Test root directory not found");
290
}
291
}
292
PKCS11_BASE = new File(cwd, PKCS11_REL_PATH.replace('/', SEP)).getAbsolutePath();
293
return PKCS11_BASE;
294
}
295
296
public static String getNSSLibDir() throws Exception {
297
return getNSSLibDir(nss_library);
298
}
299
300
static String getNSSLibDir(String library) throws Exception {
301
Path libPath = getNSSLibPath(library);
302
if (libPath == null) {
303
return null;
304
}
305
306
String libDir = String.valueOf(libPath.getParent()) + File.separatorChar;
307
System.out.println("nssLibDir: " + libDir);
308
System.setProperty("pkcs11test.nss.libdir", libDir);
309
return libDir;
310
}
311
312
private static Path getNSSLibPath() throws Exception {
313
return getNSSLibPath(nss_library);
314
}
315
316
static Path getNSSLibPath(String library) throws Exception {
317
String osid = getOsId();
318
String[] nssLibDirs = getNssLibPaths(osid);
319
if (nssLibDirs == null) {
320
System.out.println("Warning: unsupported OS: " + osid
321
+ ", please initialize NSS librarys location firstly, skipping test");
322
return null;
323
}
324
if (nssLibDirs.length == 0) {
325
System.out.println("Warning: NSS not supported on this platform, skipping test");
326
return null;
327
}
328
329
Path nssLibPath = null;
330
for (String dir : nssLibDirs) {
331
Path libPath = Paths.get(dir).resolve(System.mapLibraryName(library));
332
if (Files.exists(libPath)) {
333
nssLibPath = libPath;
334
break;
335
}
336
}
337
if (nssLibPath == null) {
338
System.out.println("Warning: can't find NSS librarys on this machine, skipping test");
339
return null;
340
}
341
return nssLibPath;
342
}
343
344
private static String getOsId() {
345
String osName = props.getProperty("os.name");
346
if (osName.startsWith("Win")) {
347
osName = "Windows";
348
} else if (osName.equals("Mac OS X")) {
349
osName = "MacOSX";
350
}
351
String osid = osName + "-" + props.getProperty("os.arch") + "-"
352
+ props.getProperty("sun.arch.data.model");
353
return osid;
354
}
355
356
static boolean isBadNSSVersion(Provider p) {
357
double nssVersion = getNSSVersion();
358
if (isNSS(p) && nssVersion >= 3.11 && nssVersion < 3.12) {
359
System.out.println("NSS 3.11 has a DER issue that recent " +
360
"version do not, skipping");
361
return true;
362
}
363
return false;
364
}
365
366
protected static void safeReload(String lib) throws Exception {
367
try {
368
System.load(lib);
369
} catch (UnsatisfiedLinkError e) {
370
if (e.getMessage().contains("already loaded")) {
371
return;
372
}
373
}
374
}
375
376
static boolean loadNSPR(String libdir) throws Exception {
377
// load NSS softoken dependencies in advance to avoid resolver issues
378
String dir = libdir.endsWith(File.separator)
379
? libdir
380
: libdir + File.separator;
381
safeReload(dir + System.mapLibraryName("nspr4"));
382
safeReload(dir + System.mapLibraryName("plc4"));
383
safeReload(dir + System.mapLibraryName("plds4"));
384
safeReload(dir + System.mapLibraryName("sqlite3"));
385
safeReload(dir + System.mapLibraryName("nssutil3"));
386
return true;
387
}
388
389
// Check the provider being used is NSS
390
public static boolean isNSS(Provider p) {
391
return p.getName().toUpperCase().equals("SUNPKCS11-NSS");
392
}
393
394
static double getNSSVersion() {
395
if (nss_version == -1)
396
getNSSInfo();
397
return nss_version;
398
}
399
400
static ECCState getNSSECC() {
401
if (nss_version == -1)
402
getNSSInfo();
403
return nss_ecc_status;
404
}
405
406
public static double getLibsoftokn3Version() {
407
if (softoken3_version == -1)
408
return getNSSInfo("softokn3");
409
return softoken3_version;
410
}
411
412
public static double getLibnss3Version() {
413
if (nss3_version == -1)
414
return getNSSInfo("nss3");
415
return nss3_version;
416
}
417
418
/* Read the library to find out the verison */
419
static void getNSSInfo() {
420
getNSSInfo(nss_library);
421
}
422
423
// Try to parse the version for the specified library.
424
// Assuming the library contains either of the following patterns:
425
// $Header: NSS <version>
426
// Version: NSS <version>
427
// Here, <version> stands for NSS version.
428
static double getNSSInfo(String library) {
429
// look for two types of headers in NSS libraries
430
String nssHeader1 = "$Header: NSS";
431
String nssHeader2 = "Version: NSS";
432
boolean found = false;
433
String s = null;
434
int i = 0;
435
Path libfile = null;
436
437
if (library.compareTo("softokn3") == 0 && softoken3_version > -1)
438
return softoken3_version;
439
if (library.compareTo("nss3") == 0 && nss3_version > -1)
440
return nss3_version;
441
442
try {
443
libfile = getNSSLibPath();
444
if (libfile == null) {
445
return 0.0;
446
}
447
try (InputStream is = Files.newInputStream(libfile)) {
448
byte[] data = new byte[1000];
449
int read = 0;
450
451
while (is.available() > 0) {
452
if (read == 0) {
453
read = is.read(data, 0, 1000);
454
} else {
455
// Prepend last 100 bytes in case the header was split
456
// between the reads.
457
System.arraycopy(data, 900, data, 0, 100);
458
read = 100 + is.read(data, 100, 900);
459
}
460
461
s = new String(data, 0, read, StandardCharsets.US_ASCII);
462
i = s.indexOf(nssHeader1);
463
if (i > 0 || (i = s.indexOf(nssHeader2)) > 0) {
464
found = true;
465
// If the nssHeader is before 920 we can break, otherwise
466
// we may not have the whole header so do another read. If
467
// no bytes are in the stream, that is ok, found is true.
468
if (i < 920) {
469
break;
470
}
471
}
472
}
473
}
474
} catch (Exception e) {
475
e.printStackTrace();
476
}
477
478
if (!found) {
479
System.out.println("lib" + library +
480
" version not found, set to 0.0: " + libfile);
481
nss_version = 0.0;
482
return nss_version;
483
}
484
485
// the index after whitespace after nssHeader
486
int afterheader = s.indexOf("NSS", i) + 4;
487
String version = String.valueOf(s.charAt(afterheader));
488
for (char c = s.charAt(++afterheader);
489
c == '.' || (c >= '0' && c <= '9');
490
c = s.charAt(++afterheader)) {
491
version += c;
492
}
493
494
// If a "dot dot" release, strip the extra dots for double parsing
495
String[] dot = version.split("\\.");
496
if (dot.length > 2) {
497
version = dot[0]+"."+dot[1];
498
for (int j = 2; dot.length > j; j++) {
499
version += dot[j];
500
}
501
}
502
503
// Convert to double for easier version value checking
504
try {
505
nss_version = Double.parseDouble(version);
506
} catch (NumberFormatException e) {
507
System.out.println("===== Content start =====");
508
System.out.println(s);
509
System.out.println("===== Content end =====");
510
System.out.println("Failed to parse lib" + library +
511
" version. Set to 0.0");
512
e.printStackTrace();
513
}
514
515
System.out.print("lib" + library + " version = "+version+". ");
516
517
// Check for ECC
518
if (s.indexOf("Basic") > 0) {
519
nss_ecc_status = ECCState.Basic;
520
System.out.println("ECC Basic.");
521
} else if (s.indexOf("Extended") > 0) {
522
nss_ecc_status = ECCState.Extended;
523
System.out.println("ECC Extended.");
524
} else {
525
System.out.println("ECC None.");
526
}
527
528
if (library.compareTo("softokn3") == 0) {
529
softoken3_version = nss_version;
530
} else if (library.compareTo("nss3") == 0) {
531
nss3_version = nss_version;
532
}
533
534
return nss_version;
535
}
536
537
// Used to set the nss_library file to search for libsoftokn3.so
538
public static void useNSS() {
539
nss_library = "nss3";
540
}
541
542
// Run NSS testing on a Provider p configured with test nss config
543
public static void testNSS(PKCS11Test test) throws Exception {
544
String nssConfig = getNssConfig();
545
if (nssConfig == null) {
546
// issue loading libraries
547
return;
548
}
549
Provider p = getSunPKCS11(nssConfig);
550
test.premain(p);
551
}
552
553
public static String getNssConfig() throws Exception {
554
String libdir = getNSSLibDir();
555
if (libdir == null) {
556
return null;
557
}
558
559
if (loadNSPR(libdir) == false) {
560
return null;
561
}
562
563
String base = getBase();
564
565
String libfile = libdir + System.mapLibraryName(nss_library);
566
567
String customDBdir = System.getProperty("CUSTOM_DB_DIR");
568
String dbdir = (customDBdir != null) ?
569
customDBdir :
570
base + SEP + "nss" + SEP + "db";
571
// NSS always wants forward slashes for the config path
572
dbdir = dbdir.replace('\\', '/');
573
574
String customConfig = System.getProperty("CUSTOM_P11_CONFIG");
575
String customConfigName = System.getProperty("CUSTOM_P11_CONFIG_NAME", "p11-nss.txt");
576
System.setProperty("pkcs11test.nss.lib", libfile);
577
System.setProperty("pkcs11test.nss.db", dbdir);
578
return (customConfig != null) ?
579
customConfig :
580
base + SEP + "nss" + SEP + customConfigName;
581
}
582
583
// Generate a vector of supported elliptic curves of a given provider
584
static List<ECParameterSpec> getKnownCurves(Provider p) throws Exception {
585
int index;
586
int begin;
587
int end;
588
String curve;
589
590
List<ECParameterSpec> results = new ArrayList<>();
591
// Get Curves to test from SunEC.
592
String kcProp = Security.getProvider("SunEC").
593
getProperty("AlgorithmParameters.EC SupportedCurves");
594
595
if (kcProp == null) {
596
throw new RuntimeException(
597
"\"AlgorithmParameters.EC SupportedCurves property\" not found");
598
}
599
600
System.out.println("Finding supported curves using list from SunEC\n");
601
index = 0;
602
for (;;) {
603
// Each set of curve names is enclosed with brackets.
604
begin = kcProp.indexOf('[', index);
605
end = kcProp.indexOf(']', index);
606
if (begin == -1 || end == -1) {
607
break;
608
}
609
610
/*
611
* Each name is separated by a comma.
612
* Just get the first name in the set.
613
*/
614
index = end + 1;
615
begin++;
616
end = kcProp.indexOf(',', begin);
617
if (end == -1) {
618
// Only one name in the set.
619
end = index -1;
620
}
621
622
curve = kcProp.substring(begin, end);
623
getSupportedECParameterSpec(curve, p)
624
.ifPresent(spec -> results.add(spec));
625
}
626
627
if (results.size() == 0) {
628
throw new RuntimeException("No supported EC curves found");
629
}
630
631
return results;
632
}
633
634
static Optional<ECParameterSpec> getSupportedECParameterSpec(String curve,
635
Provider p) throws Exception {
636
ECParameterSpec e = getECParameterSpec(p, curve);
637
System.out.print("\t "+ curve + ": ");
638
try {
639
KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", p);
640
kpg.initialize(e);
641
kpg.generateKeyPair();
642
System.out.println("Supported");
643
return Optional.of(e);
644
} catch (ProviderException ex) {
645
System.out.println("Unsupported: PKCS11: " +
646
ex.getCause().getMessage());
647
return Optional.empty();
648
} catch (InvalidAlgorithmParameterException ex) {
649
System.out.println("Unsupported: Key Length: " +
650
ex.getMessage());
651
return Optional.empty();
652
}
653
}
654
655
private static ECParameterSpec getECParameterSpec(Provider p, String name)
656
throws Exception {
657
658
AlgorithmParameters parameters =
659
AlgorithmParameters.getInstance("EC", p);
660
661
parameters.init(new ECGenParameterSpec(name));
662
663
return parameters.getParameterSpec(ECParameterSpec.class);
664
}
665
666
// Check support for a curve with a provided Vector of EC support
667
boolean checkSupport(List<ECParameterSpec> supportedEC,
668
ECParameterSpec curve) {
669
for (ECParameterSpec ec: supportedEC) {
670
if (ec.equals(curve)) {
671
return true;
672
}
673
}
674
return false;
675
}
676
677
private static Map<String,String[]> osMap;
678
679
// Location of the NSS libraries on each supported platform
680
private static Map<String, String[]> getOsMap() {
681
if (osMap != null) {
682
return osMap;
683
}
684
685
osMap = new HashMap<>();
686
osMap.put("Linux-i386-32", new String[] {
687
"/usr/lib/i386-linux-gnu/",
688
"/usr/lib32/",
689
"/usr/lib/" });
690
osMap.put("Linux-amd64-64", new String[] {
691
"/usr/lib/x86_64-linux-gnu/",
692
"/usr/lib/x86_64-linux-gnu/nss/",
693
"/usr/lib64/" });
694
osMap.put("Linux-ppc64-64", new String[] { "/usr/lib64/" });
695
osMap.put("Linux-ppc64le-64", new String[] { "/usr/lib64/" });
696
osMap.put("Linux-s390x-64", new String[] { "/usr/lib64/" });
697
osMap.put("Windows-x86-32", new String[] {});
698
osMap.put("Windows-amd64-64", new String[] {});
699
osMap.put("MacOSX-x86_64-64", new String[] {});
700
osMap.put("Linux-arm-32", new String[] {
701
"/usr/lib/arm-linux-gnueabi/nss/",
702
"/usr/lib/arm-linux-gnueabihf/nss/" });
703
osMap.put("Linux-aarch64-64", new String[] {
704
"/usr/lib/aarch64-linux-gnu/",
705
"/usr/lib/aarch64-linux-gnu/nss/",
706
"/usr/lib64/" });
707
return osMap;
708
}
709
710
private static String[] getNssLibPaths(String osId) {
711
String[] preferablePaths = getPreferableNssLibPaths(osId);
712
if (preferablePaths.length != 0) {
713
return preferablePaths;
714
} else {
715
return getOsMap().get(osId);
716
}
717
}
718
719
private static String[] getPreferableNssLibPaths(String osId) {
720
List<String> nssLibPaths = new ArrayList<>();
721
722
String customNssLibPaths = System.getProperty("test.nss.lib.paths");
723
if (customNssLibPaths == null) {
724
// If custom local NSS lib path is not provided,
725
// try to download NSS libs from artifactory
726
String path = fetchNssLib(osId);
727
if (path != null) {
728
nssLibPaths.add(path);
729
}
730
} else {
731
String[] paths = customNssLibPaths.split(",");
732
for (String path : paths) {
733
if (!path.endsWith(File.separator)) {
734
nssLibPaths.add(path + File.separator);
735
} else {
736
nssLibPaths.add(path);
737
}
738
}
739
}
740
741
return nssLibPaths.toArray(new String[nssLibPaths.size()]);
742
}
743
744
private final static char[] hexDigits = "0123456789abcdef".toCharArray();
745
746
public static String toString(byte[] b) {
747
if (b == null) {
748
return "(null)";
749
}
750
StringBuilder sb = new StringBuilder(b.length * 3);
751
for (int i = 0; i < b.length; i++) {
752
int k = b[i] & 0xff;
753
if (i != 0) {
754
sb.append(':');
755
}
756
sb.append(hexDigits[k >>> 4]);
757
sb.append(hexDigits[k & 0xf]);
758
}
759
return sb.toString();
760
}
761
762
public static byte[] parse(String s) {
763
if (s.equals("(null)")) {
764
return null;
765
}
766
try {
767
int n = s.length();
768
ByteArrayOutputStream out = new ByteArrayOutputStream(n / 3);
769
StringReader r = new StringReader(s);
770
while (true) {
771
int b1 = nextNibble(r);
772
if (b1 < 0) {
773
break;
774
}
775
int b2 = nextNibble(r);
776
if (b2 < 0) {
777
throw new RuntimeException("Invalid string " + s);
778
}
779
int b = (b1 << 4) | b2;
780
out.write(b);
781
}
782
return out.toByteArray();
783
} catch (IOException e) {
784
throw new RuntimeException(e);
785
}
786
}
787
788
private static int nextNibble(StringReader r) throws IOException {
789
while (true) {
790
int ch = r.read();
791
if (ch == -1) {
792
return -1;
793
} else if ((ch >= '0') && (ch <= '9')) {
794
return ch - '0';
795
} else if ((ch >= 'a') && (ch <= 'f')) {
796
return ch - 'a' + 10;
797
} else if ((ch >= 'A') && (ch <= 'F')) {
798
return ch - 'A' + 10;
799
}
800
}
801
}
802
803
<T> T[] concat(T[] a, T[] b) {
804
if ((b == null) || (b.length == 0)) {
805
return a;
806
}
807
T[] r = Arrays.copyOf(a, a.length + b.length);
808
System.arraycopy(b, 0, r, a.length, b.length);
809
return r;
810
}
811
812
/**
813
* Returns supported algorithms of specified type.
814
*/
815
static List<String> getSupportedAlgorithms(String type, String alg,
816
Provider p) {
817
// prepare a list of supported algorithms
818
List<String> algorithms = new ArrayList<>();
819
Set<Provider.Service> services = p.getServices();
820
for (Provider.Service service : services) {
821
if (service.getType().equals(type)
822
&& service.getAlgorithm().startsWith(alg)) {
823
algorithms.add(service.getAlgorithm());
824
}
825
}
826
return algorithms;
827
}
828
829
static byte[] generateData(int length) {
830
byte data[] = new byte[length];
831
for (int i=0; i<data.length; i++) {
832
data[i] = (byte) (i % 256);
833
}
834
return data;
835
}
836
837
private static String fetchNssLib(String osId) {
838
switch (osId) {
839
case "Windows-x86-32":
840
return fetchNssLib(WINDOWS_X86.class);
841
842
case "Windows-amd64-64":
843
return fetchNssLib(WINDOWS_X64.class);
844
845
case "MacOSX-x86_64-64":
846
return fetchNssLib(MACOSX_X64.class);
847
848
case "Linux-amd64-64":
849
return fetchNssLib(LINUX_X64.class);
850
851
default:
852
return null;
853
}
854
}
855
856
private static String fetchNssLib(Class<?> clazz) {
857
String path = null;
858
try {
859
path = ArtifactResolver.resolve(clazz).entrySet().stream()
860
.findAny().get().getValue() + File.separator + "nsslib"
861
+ File.separator;
862
} catch (ArtifactResolverException e) {
863
Throwable cause = e.getCause();
864
if (cause == null) {
865
System.out.println("Cannot resolve artifact, "
866
+ "please check if JIB jar is present in classpath.");
867
} else {
868
throw new RuntimeException("Fetch artifact failed: " + clazz
869
+ "\nPlease make sure the artifact is available.", e);
870
}
871
}
872
Policy.setPolicy(null); // Clear the policy created by JIB if any
873
return path;
874
}
875
876
protected void setCommonSystemProps() {
877
System.setProperty("java.security.debug", "true");
878
System.setProperty("NO_DEIMOS", "true");
879
System.setProperty("NO_DEFAULT", "true");
880
System.setProperty("CUSTOM_DB_DIR", TEST_CLASSES);
881
}
882
883
protected void copyNssCertKeyToClassesDir() throws IOException {
884
Path dbPath = Path.of(BASE).getParent().resolve("nss").resolve("db");
885
copyNssCertKeyToClassesDir(dbPath);
886
}
887
888
protected void copyNssCertKeyToClassesDir(Path dbPath) throws IOException {
889
Path destinationPath = Path.of(TEST_CLASSES);
890
String keyDbFile = "key3.db";
891
String certDbFile = "cert8.db";
892
893
Files.copy(dbPath.resolve(certDbFile),
894
destinationPath.resolve(certDbFile),
895
StandardCopyOption.REPLACE_EXISTING);
896
Files.copy(dbPath.resolve(keyDbFile),
897
destinationPath.resolve(keyDbFile),
898
StandardCopyOption.REPLACE_EXISTING);
899
}
900
901
@Artifact(
902
organization = "jpg.tests.jdk.nsslib",
903
name = "nsslib-windows_x64",
904
revision = "3.46-VS2017",
905
extension = "zip")
906
private static class WINDOWS_X64 { }
907
908
@Artifact(
909
organization = "jpg.tests.jdk.nsslib",
910
name = "nsslib-windows_x86",
911
revision = "3.46-VS2017",
912
extension = "zip")
913
private static class WINDOWS_X86 { }
914
915
@Artifact(
916
organization = "jpg.tests.jdk.nsslib",
917
name = "nsslib-macosx_x64",
918
revision = "3.46",
919
extension = "zip")
920
private static class MACOSX_X64 { }
921
922
@Artifact(
923
organization = "jpg.tests.jdk.nsslib",
924
name = "nsslib-linux_x64",
925
revision = "3.46",
926
extension = "zip")
927
private static class LINUX_X64 { }
928
}
929
930