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
|
/*
* Copyright (c) 2003, 2018, 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.
*/
// common infrastructure for SunPKCS11 tests
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyPairGenerator;
import java.security.NoSuchProviderException;
import java.security.Provider;
import java.security.ProviderException;
import java.security.Security;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.ECParameterSpec;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;
import java.util.Set;
import jdk.test.lib.artifacts.Artifact;
import jdk.test.lib.artifacts.ArtifactResolver;
import jdk.test.lib.artifacts.ArtifactResolverException;
public abstract class PKCS11Test {
private boolean enableSM = false;
static final Properties props = System.getProperties();
static final String PKCS11 = "PKCS11";
// directory of the test source
static final String BASE = System.getProperty("test.src", ".");
static final char SEP = File.separatorChar;
private static final String DEFAULT_POLICY =
BASE + SEP + ".." + SEP + "policy";
// directory corresponding to BASE in the /closed hierarchy
static final String CLOSED_BASE;
static {
// hack
String absBase = new File(BASE).getAbsolutePath();
int k = absBase.indexOf(SEP + "test" + SEP + "sun" + SEP);
if (k < 0) k = 0;
String p1 = absBase.substring(0, k + 6);
String p2 = absBase.substring(k + 5);
CLOSED_BASE = p1 + "closed" + p2;
// set it as a system property to make it available in policy file
System.setProperty("closed.base", CLOSED_BASE);
}
// NSS version info
public static enum ECCState { None, Basic, Extended };
static double nss_version = -1;
static ECCState nss_ecc_status = ECCState.Extended;
// The NSS library we need to search for in getNSSLibDir()
// Default is "libsoftokn3.so", listed as "softokn3"
// The other is "libnss3.so", listed as "nss3".
static String nss_library = "softokn3";
// NSS versions of each library. It is simplier to keep nss_version
// for quick checking for generic testing than many if-else statements.
static double softoken3_version = -1;
static double nss3_version = -1;
static Provider pkcs11;
// Goes through ServiceLoader instead of Provider.getInstance() since it
// works on all platforms
static {
ServiceLoader sl = ServiceLoader.load(java.security.Provider.class);
Iterator<Provider> iter = sl.iterator();
Provider p = null;
boolean found = false;
while (iter.hasNext()) {
try {
p = iter.next();
if (p.getName().equals("SunPKCS11")) {
found = true;
break;
}
} catch (Exception | ServiceConfigurationError e) {
// ignore and move on to the next one
}
}
// Nothing found through ServiceLoader; fall back to reflection
if (!found) {
try {
Class clazz = Class.forName("sun.security.pkcs11.SunPKCS11");
p = (Provider) clazz.newInstance();
} catch (Exception ex) {
ex.printStackTrace();
}
}
pkcs11 = p;
}
/*
* Use Solaris SPARC 11.2 or later to avoid an intermittent failure
* when running SunPKCS11-Solaris (8044554)
*/
static boolean isBadSolarisSparc(Provider p) {
if ("SunPKCS11-Solaris".equals(p.getName()) && badSolarisSparc) {
System.out.println("SunPKCS11-Solaris provider requires " +
"Solaris SPARC 11.2 or later, skipping");
return true;
}
return false;
}
// Return a SunPKCS11 provider configured with the specified config file
static Provider getSunPKCS11(String config) throws Exception {
if (pkcs11 == null) {
throw new NoSuchProviderException("No PKCS11 provider available");
}
return pkcs11.configure(config);
}
public abstract void main(Provider p) throws Exception;
protected boolean skipTest(Provider p) {
return false;
}
private void premain(Provider p) throws Exception {
if (skipTest(p)) {
return;
}
// set a security manager and policy before a test case runs,
// and disable them after the test case finished
try {
if (enableSM) {
System.setSecurityManager(new SecurityManager());
}
long start = System.currentTimeMillis();
System.out.printf(
"Running test with provider %s (security manager %s) ...%n",
p.getName(), enableSM ? "enabled" : "disabled");
main(p);
long stop = System.currentTimeMillis();
System.out.println("Completed test with provider " + p.getName() +
" (" + (stop - start) + " ms).");
} finally {
if (enableSM) {
System.setSecurityManager(null);
}
}
}
public static void main(PKCS11Test test) throws Exception {
main(test, null);
}
public static void main(PKCS11Test test, String[] args) throws Exception {
if (args != null) {
if (args.length > 0) {
if ("sm".equals(args[0])) {
test.enableSM = true;
} else {
throw new RuntimeException("Unknown Command, use 'sm' as "
+ "first arguemtn to enable security manager");
}
}
if (test.enableSM) {
System.setProperty("java.security.policy",
(args.length > 1) ? BASE + SEP + args[1]
: DEFAULT_POLICY);
}
}
Provider[] oldProviders = Security.getProviders();
try {
System.out.println("Beginning test run " + test.getClass().getName() + "...");
testDefault(test);
testNSS(test);
testDeimos(test);
} finally {
// NOTE: Do not place a 'return' in any finally block
// as it will suppress exceptions and hide test failures.
Provider[] newProviders = Security.getProviders();
boolean found = true;
// Do not restore providers if nothing changed. This is especailly
// useful for ./Provider/Login.sh, where a SecurityManager exists.
if (oldProviders.length == newProviders.length) {
found = false;
for (int i = 0; i<oldProviders.length; i++) {
if (oldProviders[i] != newProviders[i]) {
found = true;
break;
}
}
}
if (found) {
for (Provider p: newProviders) {
Security.removeProvider(p.getName());
}
for (Provider p: oldProviders) {
Security.addProvider(p);
}
}
}
}
public static void testDeimos(PKCS11Test test) throws Exception {
if (new File("/opt/SUNWconn/lib/libpkcs11.so").isFile() == false ||
"true".equals(System.getProperty("NO_DEIMOS"))) {
return;
}
String base = getBase();
String p11config = base + SEP + "nss" + SEP + "p11-deimos.txt";
Provider p = getSunPKCS11(p11config);
test.premain(p);
}
public static void testDefault(PKCS11Test test) throws Exception {
// run test for default configured PKCS11 providers (if any)
if ("true".equals(System.getProperty("NO_DEFAULT"))) {
return;
}
Provider[] providers = Security.getProviders();
for (int i = 0; i < providers.length; i++) {
Provider p = providers[i];
if (p.getName().startsWith("SunPKCS11-")) {
test.premain(p);
}
}
}
private static String PKCS11_BASE;
static {
try {
PKCS11_BASE = getBase();
} catch (Exception e) {
// ignore
}
}
private final static String PKCS11_REL_PATH = "sun/security/pkcs11";
public static String getBase() throws Exception {
if (PKCS11_BASE != null) {
return PKCS11_BASE;
}
File cwd = new File(System.getProperty("test.src", ".")).getCanonicalFile();
while (true) {
File file = new File(cwd, "TEST.ROOT");
if (file.isFile()) {
break;
}
cwd = cwd.getParentFile();
if (cwd == null) {
throw new Exception("Test root directory not found");
}
}
PKCS11_BASE = new File(cwd, PKCS11_REL_PATH.replace('/', SEP)).getAbsolutePath();
return PKCS11_BASE;
}
public static String getNSSLibDir() throws Exception {
return getNSSLibDir(nss_library);
}
static String getNSSLibDir(String library) throws Exception {
String osid = getOsId();
String[] nssLibDirs = getNssLibPaths(osid);
if (nssLibDirs == null) {
System.out.println("Warning: unsupported OS: " + osid
+ ", please initialize NSS librarys location firstly, skipping test");
return null;
}
if (nssLibDirs.length == 0) {
System.out.println("Warning: NSS not supported on this platform, skipping test");
return null;
}
String nssLibDir = null;
for (String dir : nssLibDirs) {
if (new File(dir).exists() &&
new File(dir + System.mapLibraryName(library)).exists()) {
nssLibDir = dir;
System.out.println("nssLibDir: " + nssLibDir);
System.setProperty("pkcs11test.nss.libdir", nssLibDir);
break;
}
}
if (nssLibDir == null) {
System.out.println("Warning: can't find NSS librarys on this machine, skipping test");
return null;
}
return nssLibDir;
}
private static String getOsId() {
String osName = props.getProperty("os.name");
if (osName.startsWith("Win")) {
osName = "Windows";
} else if (osName.equals("Mac OS X")) {
osName = "MacOSX";
}
String osid = osName + "-" + props.getProperty("os.arch") + "-"
+ props.getProperty("sun.arch.data.model");
return osid;
}
static boolean isBadNSSVersion(Provider p) {
double nssVersion = getNSSVersion();
if (isNSS(p) && nssVersion >= 3.11 && nssVersion < 3.12) {
System.out.println("NSS 3.11 has a DER issue that recent " +
"version do not, skipping");
return true;
}
return false;
}
protected static void safeReload(String lib) throws Exception {
try {
System.load(lib);
} catch (UnsatisfiedLinkError e) {
if (e.getMessage().contains("already loaded")) {
return;
}
}
}
static boolean loadNSPR(String libdir) throws Exception {
// load NSS softoken dependencies in advance to avoid resolver issues
safeReload(libdir + System.mapLibraryName("nspr4"));
safeReload(libdir + System.mapLibraryName("plc4"));
safeReload(libdir + System.mapLibraryName("plds4"));
safeReload(libdir + System.mapLibraryName("sqlite3"));
safeReload(libdir + System.mapLibraryName("nssutil3"));
return true;
}
// Check the provider being used is NSS
public static boolean isNSS(Provider p) {
return p.getName().toUpperCase().equals("SUNPKCS11-NSS");
}
static double getNSSVersion() {
if (nss_version == -1)
getNSSInfo();
return nss_version;
}
static ECCState getNSSECC() {
if (nss_version == -1)
getNSSInfo();
return nss_ecc_status;
}
public static double getLibsoftokn3Version() {
if (softoken3_version == -1)
return getNSSInfo("softokn3");
return softoken3_version;
}
public static double getLibnss3Version() {
if (nss3_version == -1)
return getNSSInfo("nss3");
return nss3_version;
}
/* Read the library to find out the verison */
static void getNSSInfo() {
getNSSInfo(nss_library);
}
// Try to parse the version for the specified library.
// Assuming the library contains either of the following patterns:
// $Header: NSS <version>
// Version: NSS <version>
// Here, <version> stands for NSS version.
static double getNSSInfo(String library) {
// look for two types of headers in NSS libraries
String nssHeader1 = "$Header: NSS";
String nssHeader2 = "Version: NSS";
boolean found = false;
String s = null;
int i = 0;
String libfile = "";
if (library.compareTo("softokn3") == 0 && softoken3_version > -1)
return softoken3_version;
if (library.compareTo("nss3") == 0 && nss3_version > -1)
return nss3_version;
try {
String libdir = getNSSLibDir();
if (libdir == null) {
return 0.0;
}
libfile = libdir + System.mapLibraryName(library);
try (FileInputStream is = new FileInputStream(libfile)) {
byte[] data = new byte[1000];
int read = 0;
while (is.available() > 0) {
if (read == 0) {
read = is.read(data, 0, 1000);
} else {
// Prepend last 100 bytes in case the header was split
// between the reads.
System.arraycopy(data, 900, data, 0, 100);
read = 100 + is.read(data, 100, 900);
}
s = new String(data, 0, read, StandardCharsets.US_ASCII);
i = s.indexOf(nssHeader1);
if (i > 0 || (i = s.indexOf(nssHeader2)) > 0) {
found = true;
// If the nssHeader is before 920 we can break, otherwise
// we may not have the whole header so do another read. If
// no bytes are in the stream, that is ok, found is true.
if (i < 920) {
break;
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
if (!found) {
System.out.println("lib" + library +
" version not found, set to 0.0: " + libfile);
nss_version = 0.0;
return nss_version;
}
// the index after whitespace after nssHeader
int afterheader = s.indexOf("NSS", i) + 4;
String version = String.valueOf(s.charAt(afterheader));
for (char c = s.charAt(++afterheader);
c == '.' || (c >= '0' && c <= '9');
c = s.charAt(++afterheader)) {
version += c;
}
// If a "dot dot" release, strip the extra dots for double parsing
String[] dot = version.split("\\.");
if (dot.length > 2) {
version = dot[0]+"."+dot[1];
for (int j = 2; dot.length > j; j++) {
version += dot[j];
}
}
// Convert to double for easier version value checking
try {
nss_version = Double.parseDouble(version);
} catch (NumberFormatException e) {
System.out.println("===== Content start =====");
System.out.println(s);
System.out.println("===== Content end =====");
System.out.println("Failed to parse lib" + library +
" version. Set to 0.0");
e.printStackTrace();
}
System.out.print("lib" + library + " version = "+version+". ");
// Check for ECC
if (s.indexOf("Basic") > 0) {
nss_ecc_status = ECCState.Basic;
System.out.println("ECC Basic.");
} else if (s.indexOf("Extended") > 0) {
nss_ecc_status = ECCState.Extended;
System.out.println("ECC Extended.");
} else {
System.out.println("ECC None.");
}
if (library.compareTo("softokn3") == 0) {
softoken3_version = nss_version;
} else if (library.compareTo("nss3") == 0) {
nss3_version = nss_version;
}
return nss_version;
}
// Used to set the nss_library file to search for libsoftokn3.so
public static void useNSS() {
nss_library = "nss3";
}
public static void testNSS(PKCS11Test test) throws Exception {
String libdir = getNSSLibDir();
if (libdir == null) {
return;
}
String base = getBase();
if (loadNSPR(libdir) == false) {
return;
}
String libfile = libdir + System.mapLibraryName(nss_library);
String customDBdir = System.getProperty("CUSTOM_DB_DIR");
String dbdir = (customDBdir != null) ?
customDBdir :
base + SEP + "nss" + SEP + "db";
// NSS always wants forward slashes for the config path
dbdir = dbdir.replace('\\', '/');
String customConfig = System.getProperty("CUSTOM_P11_CONFIG");
String customConfigName = System.getProperty("CUSTOM_P11_CONFIG_NAME", "p11-nss.txt");
String p11config = (customConfig != null) ?
customConfig :
base + SEP + "nss" + SEP + customConfigName;
System.setProperty("pkcs11test.nss.lib", libfile);
System.setProperty("pkcs11test.nss.db", dbdir);
Provider p = getSunPKCS11(p11config);
test.premain(p);
}
// Generate a vector of supported elliptic curves of a given provider
static List<ECParameterSpec> getKnownCurves(Provider p) throws Exception {
int index;
int begin;
int end;
String curve;
List<ECParameterSpec> results = new ArrayList<>();
// Get Curves to test from SunEC.
String kcProp = Security.getProvider("SunEC").
getProperty("AlgorithmParameters.EC SupportedCurves");
if (kcProp == null) {
throw new RuntimeException(
"\"AlgorithmParameters.EC SupportedCurves property\" not found");
}
System.out.println("Finding supported curves using list from SunEC\n");
index = 0;
for (;;) {
// Each set of curve names is enclosed with brackets.
begin = kcProp.indexOf('[', index);
end = kcProp.indexOf(']', index);
if (begin == -1 || end == -1) {
break;
}
/*
* Each name is separated by a comma.
* Just get the first name in the set.
*/
index = end + 1;
begin++;
end = kcProp.indexOf(',', begin);
if (end == -1) {
// Only one name in the set.
end = index -1;
}
curve = kcProp.substring(begin, end);
getSupportedECParameterSpec(curve, p)
.ifPresent(spec -> results.add(spec));
}
if (results.size() == 0) {
throw new RuntimeException("No supported EC curves found");
}
return results;
}
static Optional<ECParameterSpec> getSupportedECParameterSpec(String curve,
Provider p) throws Exception {
ECParameterSpec e = getECParameterSpec(p, curve);
System.out.print("\t "+ curve + ": ");
try {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", p);
kpg.initialize(e);
kpg.generateKeyPair();
System.out.println("Supported");
return Optional.of(e);
} catch (ProviderException ex) {
System.out.println("Unsupported: PKCS11: " +
ex.getCause().getMessage());
return Optional.empty();
} catch (InvalidAlgorithmParameterException ex) {
System.out.println("Unsupported: Key Length: " +
ex.getMessage());
return Optional.empty();
}
}
private static ECParameterSpec getECParameterSpec(Provider p, String name)
throws Exception {
AlgorithmParameters parameters =
AlgorithmParameters.getInstance("EC", p);
parameters.init(new ECGenParameterSpec(name));
return parameters.getParameterSpec(ECParameterSpec.class);
}
// Check support for a curve with a provided Vector of EC support
boolean checkSupport(List<ECParameterSpec> supportedEC,
ECParameterSpec curve) {
for (ECParameterSpec ec: supportedEC) {
if (ec.equals(curve)) {
return true;
}
}
return false;
}
private static Map<String,String[]> osMap;
// Location of the NSS libraries on each supported platform
private static Map<String, String[]> getOsMap() {
if (osMap != null) {
return osMap;
}
osMap = new HashMap<>();
osMap.put("SunOS-sparc-32", new String[] { "/usr/lib/mps/" });
osMap.put("SunOS-sparcv9-64", new String[] { "/usr/lib/mps/64/" });
osMap.put("SunOS-x86-32", new String[] { "/usr/lib/mps/" });
osMap.put("SunOS-amd64-64", new String[] { "/usr/lib/mps/64/" });
osMap.put("Linux-i386-32", new String[] {
"/usr/lib/i386-linux-gnu/",
"/usr/lib32/",
"/usr/lib/" });
osMap.put("Linux-amd64-64", new String[] {
"/usr/lib/x86_64-linux-gnu/",
"/usr/lib/x86_64-linux-gnu/nss/",
"/usr/lib64/" });
osMap.put("Linux-ppc64-64", new String[] { "/usr/lib64/" });
osMap.put("Linux-ppc64le-64", new String[] { "/usr/lib64/" });
osMap.put("Linux-s390x-64", new String[] { "/usr/lib64/" });
osMap.put("Windows-x86-32", new String[] {});
osMap.put("Windows-amd64-64", new String[] {});
osMap.put("MacOSX-x86_64-64", new String[] {});
osMap.put("Linux-arm-32", new String[] {
"/usr/lib/arm-linux-gnueabi/nss/",
"/usr/lib/arm-linux-gnueabihf/nss/" });
osMap.put("Linux-aarch64-64", new String[] {
"/usr/lib/aarch64-linux-gnu/",
"/usr/lib/aarch64-linux-gnu/nss/" });
return osMap;
}
private static String[] getNssLibPaths(String osId) {
String[] preferablePaths = getPreferableNssLibPaths(osId);
if (preferablePaths.length != 0) {
return preferablePaths;
} else {
return getOsMap().get(osId);
}
}
private static String[] getPreferableNssLibPaths(String osId) {
List<String> nssLibPaths = new ArrayList<>();
String customNssLibPaths = System.getProperty("test.nss.lib.paths");
if (customNssLibPaths == null) {
// If custom local NSS lib path is not provided,
// try to download NSS libs from artifactory
String path = fetchNssLib(osId);
if (path != null) {
nssLibPaths.add(path);
}
} else {
String[] paths = customNssLibPaths.split(",");
for (String path : paths) {
if (!path.endsWith(File.separator)) {
nssLibPaths.add(path + File.separator);
} else {
nssLibPaths.add(path);
}
}
}
return nssLibPaths.toArray(new String[nssLibPaths.size()]);
}
private final static char[] hexDigits = "0123456789abcdef".toCharArray();
private static final String distro = distro();
static final boolean badSolarisSparc =
System.getProperty("os.name").equals("SunOS") &&
System.getProperty("os.arch").equals("sparcv9") &&
System.getProperty("os.version").compareTo("5.11") <= 0 &&
getDistro().compareTo("11.2") < 0;
public static String toString(byte[] b) {
if (b == null) {
return "(null)";
}
StringBuilder sb = new StringBuilder(b.length * 3);
for (int i = 0; i < b.length; i++) {
int k = b[i] & 0xff;
if (i != 0) {
sb.append(':');
}
sb.append(hexDigits[k >>> 4]);
sb.append(hexDigits[k & 0xf]);
}
return sb.toString();
}
public static byte[] parse(String s) {
if (s.equals("(null)")) {
return null;
}
try {
int n = s.length();
ByteArrayOutputStream out = new ByteArrayOutputStream(n / 3);
StringReader r = new StringReader(s);
while (true) {
int b1 = nextNibble(r);
if (b1 < 0) {
break;
}
int b2 = nextNibble(r);
if (b2 < 0) {
throw new RuntimeException("Invalid string " + s);
}
int b = (b1 << 4) | b2;
out.write(b);
}
return out.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static int nextNibble(StringReader r) throws IOException {
while (true) {
int ch = r.read();
if (ch == -1) {
return -1;
} else if ((ch >= '0') && (ch <= '9')) {
return ch - '0';
} else if ((ch >= 'a') && (ch <= 'f')) {
return ch - 'a' + 10;
} else if ((ch >= 'A') && (ch <= 'F')) {
return ch - 'A' + 10;
}
}
}
<T> T[] concat(T[] a, T[] b) {
if ((b == null) || (b.length == 0)) {
return a;
}
T[] r = Arrays.copyOf(a, a.length + b.length);
System.arraycopy(b, 0, r, a.length, b.length);
return r;
}
/**
* Returns supported algorithms of specified type.
*/
static List<String> getSupportedAlgorithms(String type, String alg,
Provider p) {
// prepare a list of supported algorithms
List<String> algorithms = new ArrayList<>();
Set<Provider.Service> services = p.getServices();
for (Provider.Service service : services) {
if (service.getType().equals(type)
&& service.getAlgorithm().startsWith(alg)) {
algorithms.add(service.getAlgorithm());
}
}
return algorithms;
}
/**
* Get the identifier for the operating system distribution
*/
static String getDistro() {
return distro;
}
private static String distro() {
if (props.getProperty("os.name").equals("SunOS")) {
try (BufferedReader in =
new BufferedReader(new InputStreamReader(
Runtime.getRuntime().exec("uname -v").getInputStream()))) {
return in.readLine();
} catch (Exception e) {
throw new RuntimeException("Failed to determine distro.", e);
}
} else {
// Not used outside Solaris
return null;
}
}
static byte[] generateData(int length) {
byte data[] = new byte[length];
for (int i=0; i<data.length; i++) {
data[i] = (byte) (i % 256);
}
return data;
}
private static String fetchNssLib(String osId) {
switch (osId) {
case "Windows-x86-32":
return fetchNssLib(WINDOWS_X86.class);
case "Windows-amd64-64":
return fetchNssLib(WINDOWS_X64.class);
case "MacOSX-x86_64-64":
return fetchNssLib(MACOSX_X64.class);
default:
return null;
}
}
private static String fetchNssLib(Class<?> clazz) {
String path = null;
try {
path = ArtifactResolver.resolve(clazz).entrySet().stream()
.findAny().get().getValue() + File.separator + "nsslib"
+ File.separator;
} catch (ArtifactResolverException e) {
Throwable cause = e.getCause();
if (cause == null) {
System.out.println("Cannot resolve artifact, "
+ "please check if JIB jar is present in classpath.");
} else {
throw new RuntimeException("Fetch artifact failed: " + clazz
+ "\nPlease make sure the artifact is available.");
}
}
return path;
}
@Artifact(
organization = "jpg.tests.jdk.nsslib",
name = "nsslib-windows_x64",
revision = "3.35",
extension = "zip")
private static class WINDOWS_X64 { }
@Artifact(
organization = "jpg.tests.jdk.nsslib",
name = "nsslib-windows_x86",
revision = "3.35",
extension = "zip")
private static class WINDOWS_X86 { }
@Artifact(
organization = "jpg.tests.jdk.nsslib",
name = "nsslib-macosx_x64",
revision = "3.35",
extension = "zip")
private static class MACOSX_X64 { }
}
|