# HG changeset patch # User amurillo # Date 1442328464 25200 # Node ID e77968f864eb64500bc951b7f530ff7f84e5c573 # Parent 7ecf45f5fa4651ecd4db9f1661ad8265eb5be264# Parent afc55db01c8e5933de2ed9a0898f463ab5645b31 Merge diff -r 7ecf45f5fa46 -r e77968f864eb .hgtags --- a/.hgtags Thu Sep 10 14:55:20 2015 -0700 +++ b/.hgtags Tue Sep 15 07:47:44 2015 -0700 @@ -323,3 +323,4 @@ 0940ce86c614458f5bdd72278b190abbf36b7b45 jdk9-b78 d99c2ffdd0f15753e69126583688f2f075a0a5e8 jdk9-b79 4947810137ae53abba3028cc366af953d90fa81a jdk9-b80 +fdc13a2d32867ca3c57b7fa2620c6b59c83168cb jdk9-b81 diff -r 7ecf45f5fa46 -r e77968f864eb make/Tools.gmk --- a/make/Tools.gmk Thu Sep 10 14:55:20 2015 -0700 +++ b/make/Tools.gmk Tue Sep 15 07:47:44 2015 -0700 @@ -159,28 +159,6 @@ ########################################################################################## -# Tools needed on solaris because OBJCOPY is broken. - -ifeq ($(OPENJDK_TARGET_OS), solaris) - $(eval $(call SetupNativeCompilation,ADD_GNU_DEBUGLINK, \ - SRC := $(JDK_TOPDIR)/make/src/native/add_gnu_debuglink, \ - TOOLCHAIN := TOOLCHAIN_BUILD, \ - LDFLAGS := -lelf, \ - OBJECT_DIR := $(BUILDTOOLS_OUTPUTDIR)/objs/add_gnu_debuglink, \ - OUTPUT_DIR := $(BUILDTOOLS_OUTPUTDIR)/bin, \ - PROGRAM := add_gnu_debuglink)) - - $(eval $(call SetupNativeCompilation,FIX_EMPTY_SEC_HDR_FLAGS, \ - SRC := $(JDK_TOPDIR)/make/src/native/fix_empty_sec_hdr_flags, \ - TOOLCHAIN := TOOLCHAIN_BUILD, \ - LDFLAGS := -lelf, \ - OBJECT_DIR := $(BUILDTOOLS_OUTPUTDIR)/objs/fix_empty_sec_hdr_flags, \ - OUTPUT_DIR := $(BUILDTOOLS_OUTPUTDIR)/bin, \ - PROGRAM := fix_empty_sec_hdr_flags)) - - BUILD_TOOLS_JDK += $(ADD_GNU_DEBUGLINK) $(FIX_EMPTY_SEC_HDR_FLAGS) -endif - $(BUILD_TOOLS_JDK): $(BUILD_INTERIM_JIMAGE) $(COPY_JIMAGE_SERVICE_PROVIDER) java-tools: $(BUILD_TOOLS_JDK) diff -r 7ecf45f5fa46 -r e77968f864eb make/launcher/LauncherCommon.gmk --- a/make/launcher/LauncherCommon.gmk Thu Sep 10 14:55:20 2015 -0700 +++ b/make/launcher/LauncherCommon.gmk Tue Sep 15 07:47:44 2015 -0700 @@ -28,9 +28,6 @@ # Prepare the find cache. $(eval $(call FillCacheFind, $(JDK_TOPDIR)/src/java.base/share/native/launcher)) -# Build tools -include Tools.gmk - # When building a legacy overlay image (on solaris 64 bit), the launchers # need to be built with a different rpath and a different output dir. ifeq ($(OVERLAY_IMAGES), true) diff -r 7ecf45f5fa46 -r e77968f864eb make/lib/LibCommon.gmk --- a/make/lib/LibCommon.gmk Thu Sep 10 14:55:20 2015 -0700 +++ b/make/lib/LibCommon.gmk Tue Sep 15 07:47:44 2015 -0700 @@ -27,9 +27,6 @@ include MakeBase.gmk include NativeCompilation.gmk -# Build tools -include Tools.gmk - GLOBAL_VERSION_INFO_RESOURCE := $(JDK_TOPDIR)/src/java.base/windows/native/common/version.rc # Absolute paths to lib files on windows for use in LDFLAGS. Should figure out a more diff -r 7ecf45f5fa46 -r e77968f864eb make/src/classes/build/tools/cldrconverter/ResourceBundleGenerator.java --- a/make/src/classes/build/tools/cldrconverter/ResourceBundleGenerator.java Thu Sep 10 14:55:20 2015 -0700 +++ b/make/src/classes/build/tools/cldrconverter/ResourceBundleGenerator.java Tue Sep 15 07:47:44 2015 -0700 @@ -266,22 +266,47 @@ out.println((CLDRConverter.isBaseModule ? "package sun.util.cldr;\n\n" : "package sun.util.resources.cldr.provider;\n\n") + "import java.util.HashMap;\n" + + "import java.util.Locale;\n" + "import java.util.Map;\n" - + "import java.util.ListResourceBundle;\n" + "import sun.util.locale.provider.LocaleProviderAdapter;\n" + "import sun.util.locale.provider.LocaleDataMetaInfo;\n"); - out.printf("public class %s extends ListResourceBundle implements LocaleDataMetaInfo {\n", className); - out.println(" @Override\n" + - " protected final Object[][] getContents() {\n" + - " final Object[][] data = new Object[][] {"); + out.printf("public class %s implements LocaleDataMetaInfo {\n", className); + out.println(" private static final Map resourceNameToLocales = new HashMap<>();\n" + + (CLDRConverter.isBaseModule ? + " private static final Map parentLocalesMap = new HashMap<>();\n\n" : "\n") + + " static {\n"); + for (String key : metaInfo.keySet()) { - out.printf(" { \"%s\",\n", key); - out.printf(" \"%s\" },\n", + if (key.startsWith(CLDRConverter.PARENT_LOCALE_PREFIX)) { + String parentTag = key.substring(CLDRConverter.PARENT_LOCALE_PREFIX.length()); + if ("root".equals(parentTag)) { + out.printf(" parentLocalesMap.put(Locale.ROOT,\n"); + } else { + out.printf(" parentLocalesMap.put(Locale.forLanguageTag(\"%s\"),\n", + parentTag); + } + String[] childlen = toLocaleList(metaInfo.get(key), true).split(" "); + out.printf(" new String[] {\n" + + " "); + int count = 0; + for (int i = 0; i < childlen.length; i++) { + String child = childlen[i]; + out.printf("\"%s\", ", child); + count += child.length() + 4; + if (i != childlen.length - 1 && count > 64) { + out.printf("\n "); + count = 0; + } + } + out.printf("\n });\n"); + } else { + out.printf(" resourceNameToLocales.put(\"%s\",\n", key); + out.printf(" \"%s\");\n", toLocaleList(key.equals("FormatData") ? metaInfo.get("AvailableLocales") : - metaInfo.get(key), - key.startsWith(CLDRConverter.PARENT_LOCALE_PREFIX))); + metaInfo.get(key), false)); + } } - out.println(" };\n return data;\n }\n\n"); + out.println(" }\n\n"); out.println(" @Override\n" + " public LocaleProviderAdapter.Type getType() {\n" + @@ -290,19 +315,13 @@ out.println(" @Override\n" + " public String availableLanguageTags(String category) {\n" + - " return getString(category);\n" + - " };\n\n"); + " return resourceNameToLocales.getOrDefault(category, \"\");\n" + + " }\n\n"); if (CLDRConverter.isBaseModule) { - out.printf(" public Map parentLocales() {\n" + - " Map ret = new HashMap<>();\n" + - " keySet().stream()\n" + - " .filter(key -> key.startsWith(\"%s\"))\n" + - " .forEach(key -> ret.put(key.substring(%d), getString(key)));\n" + - " return ret.isEmpty() ? null : ret;\n" + - " };\n}", - CLDRConverter.PARENT_LOCALE_PREFIX, - CLDRConverter.PARENT_LOCALE_PREFIX.length()); + out.printf(" public Map parentLocales() {\n" + + " return parentLocalesMap;\n" + + " }\n}"); } else { out.println("}"); } diff -r 7ecf45f5fa46 -r e77968f864eb make/src/native/add_gnu_debuglink/add_gnu_debuglink.c --- a/make/src/native/add_gnu_debuglink/add_gnu_debuglink.c Thu Sep 10 14:55:20 2015 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,285 +0,0 @@ -/* - * Copyright (c) 2012, 2013, 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. - * - */ - -/* - * Name: add_gnu_debuglink.c - * - * Description: Add a ".gnu_debuglink" section that refers to the specified - * debug_info_path to the specified ELF object. - * - * This program is adapted from the example program shown on the - * elf(3elf) man page and from code from the Solaris compiler - * driver. - */ - -/* - * needed to define SHF_EXCLUDE - */ -#define ELF_TARGET_ALL - -#include -#include -#include -#include -#include -#include - -static void failure(void); -static unsigned int gnu_debuglink_crc32(unsigned int crc, unsigned char *buf, - size_t len); - -void -main(int argc, char ** argv) { - /* new ELF section name */ - static char SEC_NAME[] = ".gnu_debuglink"; - - unsigned char buffer[8 * 1024]; /* I/O buffer */ - int buffer_len; /* buffer length */ - char * debug_info_path; /* debug info path */ - void * ehdr; /* ELF header */ - Elf * elf; /* ELF descriptor */ - char * elf_ident; /* ELF identity string */ - char * elf_obj; /* elf_obj file */ - int fd; /* descriptor for files */ - unsigned int file_crc = 0; /* CRC for debug info file */ - int is_elfclass64; /* is an ELFCLASS64 file? */ - Elf_Data * link_dat; /* ELF data for new debug info link */ - Elf_Data * name_dat; /* ELF data for new section name */ - Elf_Scn * new_scn; /* new ELF section descriptor */ - void * new_shdr; /* new ELF section header */ - Elf_Scn * scn; /* ELF section descriptor */ - void * shdr; /* ELF section header */ - - if (argc != 3) { - (void) fprintf(stderr, "Usage: %s debug_info_path elf_obj\n", argv[0]); - exit(2); - } - - debug_info_path = argv[1]; /* save for later */ - if ((fd = open(debug_info_path, O_RDONLY)) == -1) { - (void) fprintf(stderr, "%s: cannot open file.\n", debug_info_path); - exit(3); - } - - (void) printf("Computing CRC for '%s'\n", debug_info_path); - (void) fflush(stdout); - /* compute CRC for the debug info file */ - for (;;) { - int len = read(fd, buffer, sizeof buffer); - if (len <= 0) { - break; - } - file_crc = gnu_debuglink_crc32(file_crc, buffer, len); - } - (void) close(fd); - - /* open the elf_obj */ - elf_obj = argv[2]; - if ((fd = open(elf_obj, O_RDWR)) == -1) { - (void) fprintf(stderr, "%s: cannot open file.\n", elf_obj); - exit(4); - } - - (void) printf("Opening '%s' for update\n", elf_obj); - (void) fflush(stdout); - (void) elf_version(EV_CURRENT); /* coordinate ELF versions */ - - /* obtain the ELF descriptors from the input file */ - if ((elf = elf_begin(fd, ELF_C_RDWR, NULL)) == NULL) { - failure(); - } - - /* determine if ELFCLASS64 or not? */ - elf_ident = elf_getident(elf, NULL); - is_elfclass64 = (elf_ident[EI_CLASS] == ELFCLASS64); - - /* get the ELF header */ - if (is_elfclass64) { - ehdr = elf64_getehdr(elf); - } else { - ehdr = elf32_getehdr(elf); - } - if (ehdr == NULL) { - failure(); - } - - /* get the ELF section descriptor */ - if (is_elfclass64) { - scn = elf_getscn(elf, ((Elf64_Ehdr *) ehdr)->e_shstrndx); - } else { - scn = elf_getscn(elf, ((Elf32_Ehdr *) ehdr)->e_shstrndx); - } - if (scn == NULL) { - failure(); - } - - /* get the section header */ - if (is_elfclass64) { - shdr = elf64_getshdr(scn); - } else { - shdr = elf32_getshdr(scn); - } - if (shdr == NULL) { - failure(); - } - - (void) printf("Adding ELF data for new section name\n"); - (void) fflush(stdout); - name_dat = elf_newdata(scn); - name_dat->d_buf = (void *) SEC_NAME; - if (is_elfclass64) { - name_dat->d_off = ((Elf64_Shdr *) shdr)->sh_size + 1; - } else { - name_dat->d_off = ((Elf32_Shdr *) shdr)->sh_size + 1; - } - name_dat->d_align = 1; - name_dat->d_size = strlen(SEC_NAME) + 1; - - new_scn = elf_newscn(elf); - - if (is_elfclass64) { - new_shdr = elf64_getshdr(new_scn); - ((Elf64_Shdr *) new_shdr)->sh_flags = SHF_EXCLUDE; - ((Elf64_Shdr *) new_shdr)->sh_type = SHT_PROGBITS; - ((Elf64_Shdr *) new_shdr)->sh_name = ((Elf64_Shdr *) shdr)->sh_size; - ((Elf64_Shdr *) new_shdr)->sh_addralign = 1; - ((Elf64_Shdr *) shdr)->sh_size += (strlen(SEC_NAME) + 1); - } else { - new_shdr = elf32_getshdr(new_scn); - ((Elf32_Shdr *) new_shdr)->sh_flags = SHF_EXCLUDE; - ((Elf32_Shdr *) new_shdr)->sh_type = SHT_PROGBITS; - ((Elf32_Shdr *) new_shdr)->sh_name = ((Elf32_Shdr *) shdr)->sh_size; - ((Elf32_Shdr *) new_shdr)->sh_addralign = 1; - ((Elf32_Shdr *) shdr)->sh_size += (strlen(SEC_NAME) + 1); - } - - (void) printf("Adding ELF data for debug_info_path value\n"); - (void) fflush(stdout); - (void) memset(buffer, 0, sizeof buffer); - buffer_len = strlen(debug_info_path) + 1; /* +1 for NUL */ - (void) strncpy((char *) buffer, debug_info_path, buffer_len); - if (buffer_len % 4 != 0) { - /* not on a 4 byte boundary so pad to the next one */ - buffer_len += (4 - buffer_len % 4); - } - /* save the CRC */ - (void) memcpy(&buffer[buffer_len], &file_crc, sizeof file_crc); - buffer_len += sizeof file_crc; - - link_dat = elf_newdata(new_scn); - link_dat->d_type = ELF_T_BYTE; - link_dat->d_size = buffer_len; - link_dat->d_buf = buffer; - link_dat->d_align = 1; - - (void) printf("Saving updates to '%s'\n", elf_obj); - (void) fflush(stdout); - (void) elf_update(elf, ELF_C_NULL); /* recalc ELF memory structures */ - (void) elf_update(elf, ELF_C_WRITE); /* write out changes to ELF obj */ - (void) elf_end(elf); /* done with ELF obj */ - (void) close(fd); - - (void) printf("Done updating '%s'\n", elf_obj); - (void) fflush(stdout); - exit(0); -} /* end main */ - - -static void -failure() { - (void) fprintf(stderr, "%s\n", elf_errmsg(elf_errno())); - exit(5); -} - - -/* - * The CRC used in gnu_debuglink, retrieved from - * http://sourceware.org/gdb/current/onlinedocs/gdb/Separate-Debug-Files.html#Separate-Debug-Files. - */ - -static unsigned int -gnu_debuglink_crc32(unsigned int crc, unsigned char *buf, size_t len) { - static const unsigned int crc32_table[256] = { - 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, - 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, - 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, - 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, - 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, - 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, - 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, - 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, - 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, - 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, - 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, - 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, - 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, - 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, - 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, - 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, - 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, - 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, - 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, - 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, - 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, - 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, - 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, - 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, - 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, - 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, - 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, - 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, - 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, - 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, - 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, - 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, - 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, - 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, - 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, - 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, - 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, - 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, - 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, - 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, - 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, - 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, - 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, - 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, - 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, - 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, - 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, - 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, - 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, - 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, - 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, - 0x2d02ef8d - }; - - unsigned char *end; - - crc = ~crc & 0xffffffff; - for (end = buf + len; buf < end; ++buf) { - crc = crc32_table[(crc ^ *buf) & 0xff] ^ (crc >> 8); - } - return ~crc & 0xffffffff; -} diff -r 7ecf45f5fa46 -r e77968f864eb make/src/native/fix_empty_sec_hdr_flags/fix_empty_sec_hdr_flags.c --- a/make/src/native/fix_empty_sec_hdr_flags/fix_empty_sec_hdr_flags.c Thu Sep 10 14:55:20 2015 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,181 +0,0 @@ -/* - * Copyright (c) 2012, 2013, 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. - * - */ - -/* - * Name: fix_empty_sec_hdr_flags.c - * - * Description: Remove the SHF_ALLOC flag from "empty" section headers. - * An "empty" section header has sh_addr == 0 and sh_size == 0. - * - * This program is adapted from the example program shown on the - * elf(3elf) man page and from code from the Solaris compiler - * driver. - */ - -#include -#include -#include -#include -#include -#include - -static void failure(void); - -void -main(int argc, char ** argv) { - void * ehdr; /* ELF header */ - unsigned int i; /* section counter */ - int fd; /* descriptor for file */ - Elf * elf; /* ELF descriptor */ - char * elf_ident; /* ELF identity string */ - char * elf_obj; /* elf_obj file */ - int fix_count; /* number of flags fixed */ - int is_elfclass64; /* is an ELFCLASS64 file? */ - Elf_Scn * scn; /* ELF section descriptor */ - void * shdr; /* ELF section header */ - Elf_Data * shstrtab; /* ELF section header string table */ - - if (argc != 2) { - (void) fprintf(stderr, "Usage: %s elf_obj\n", argv[0]); - exit(2); - } - - /* open the elf_obj */ - elf_obj = argv[1]; - if ((fd = open(elf_obj, O_RDWR)) == -1) { - (void) fprintf(stderr, "%s: cannot open file.\n", elf_obj); - exit(3); - } - - (void) printf("Opening '%s' for update\n", elf_obj); - (void) fflush(stdout); - (void) elf_version(EV_CURRENT); /* coordinate ELF versions */ - - /* obtain the ELF descriptors from the input file */ - if ((elf = elf_begin(fd, ELF_C_RDWR, NULL)) == NULL) { - failure(); - } - - /* determine if ELFCLASS64 or not? */ - elf_ident = elf_getident(elf, NULL); - is_elfclass64 = (elf_ident[EI_CLASS] == ELFCLASS64); - - /* get the ELF header */ - if (is_elfclass64) { - ehdr = elf64_getehdr(elf); - } else { - ehdr = elf32_getehdr(elf); - } - if (ehdr == NULL) { - failure(); - } - - /* get the ELF section descriptor */ - if (is_elfclass64) { - scn = elf_getscn(elf, ((Elf64_Ehdr *) ehdr)->e_shstrndx); - } else { - scn = elf_getscn(elf, ((Elf32_Ehdr *) ehdr)->e_shstrndx); - } - if (scn == NULL) { - failure(); - } - - /* get the section header string table */ - shstrtab = elf_getdata(scn, NULL); - if (shstrtab == NULL) { - failure(); - } - - fix_count = 0; - - /* traverse the sections of the input file */ - for (i = 1, scn = NULL; scn = elf_nextscn(elf, scn); i++) { - int has_flag_set; /* is SHF_ALLOC flag set? */ - int is_empty; /* is section empty? */ - char * name; /* short hand pointer */ - - /* get the section header */ - if (is_elfclass64) { - shdr = elf64_getshdr(scn); - } else { - shdr = elf32_getshdr(scn); - } - if (shdr == NULL) { - failure(); - } - - if (is_elfclass64) { - name = (char *)shstrtab->d_buf + ((Elf64_Shdr *) shdr)->sh_name; - } else { - name = (char *)shstrtab->d_buf + ((Elf32_Shdr *) shdr)->sh_name; - } - - if (is_elfclass64) { - has_flag_set = ((Elf64_Shdr *) shdr)->sh_flags & SHF_ALLOC; - is_empty = ((Elf64_Shdr *) shdr)->sh_addr == 0 && - ((Elf64_Shdr *) shdr)->sh_size == 0; - } else { - has_flag_set = ((Elf32_Shdr *) shdr)->sh_flags & SHF_ALLOC; - is_empty = ((Elf32_Shdr *) shdr)->sh_addr == 0 && - ((Elf32_Shdr *) shdr)->sh_size == 0; - } - - if (is_empty && has_flag_set) { - (void) printf("section[%u] '%s' is empty, " - "but SHF_ALLOC flag is set.\n", i, name); - (void) printf("Clearing the SHF_ALLOC flag.\n"); - - if (is_elfclass64) { - ((Elf64_Shdr *) shdr)->sh_flags &= ~SHF_ALLOC; - } else { - ((Elf32_Shdr *) shdr)->sh_flags &= ~SHF_ALLOC; - } - fix_count++; - } - } /* end for each ELF section */ - - if (fix_count > 0) { - (void) printf("Saving %d updates to '%s'\n", fix_count, elf_obj); - (void) fflush(stdout); - (void) elf_update(elf, ELF_C_NULL); /* recalc ELF memory structures */ - (void) elf_update(elf, ELF_C_WRITE); /* write out changes to ELF obj */ - } else { - (void) printf("No SHF_ALLOC flags needed to be cleared.\n"); - } - - (void) elf_end(elf); /* done with ELF obj */ - (void) close(fd); - - (void) printf("Done %s '%s'\n", - (fix_count > 0) ? "updating" : "with", elf_obj); - (void) fflush(stdout); - exit(0); -} /* end main */ - - -static void -failure() { - (void) fprintf(stderr, "%s\n", elf_errmsg(elf_errno())); - exit(6); -} diff -r 7ecf45f5fa46 -r e77968f864eb src/java.base/linux/native/libjava/ProcessHandleImpl_linux.c --- a/src/java.base/linux/native/libjava/ProcessHandleImpl_linux.c Thu Sep 10 14:55:20 2015 -0700 +++ b/src/java.base/linux/native/libjava/ProcessHandleImpl_linux.c Tue Sep 15 07:47:44 2015 -0700 @@ -141,17 +141,21 @@ struct stat stat_buf; /* + * Stat /proc/ to get the user id + */ + snprintf(fn, sizeof fn, "/proc/%d", pid); + if (stat(fn, &stat_buf) == 0) { + unix_getUserInfo(env, jinfo, stat_buf.st_uid); + } + + /* * Try to open /proc//cmdline */ - snprintf(fn, sizeof fn, "/proc/%d/cmdline", pid); + strncat(fn, "/cmdline", sizeof fn - strnlen(fn, sizeof fn) - 1); if ((fd = open(fn, O_RDONLY)) < 0) { return; } - if (fstat(fd, &stat_buf) == 0) { - unix_getUserInfo(env, jinfo, stat_buf.st_uid); - } - do { // Block to break out of on errors int i, truncated = 0; int count; diff -r 7ecf45f5fa46 -r e77968f864eb src/java.base/macosx/native/libosxsecurity/KeystoreImpl.m --- a/src/java.base/macosx/native/libosxsecurity/KeystoreImpl.m Thu Sep 10 14:55:20 2015 -0700 +++ b/src/java.base/macosx/native/libosxsecurity/KeystoreImpl.m Tue Sep 15 07:47:44 2015 -0700 @@ -508,7 +508,7 @@ SecKeychainRef defaultKeychain = NULL; SecKeychainCopyDefault(&defaultKeychain); - SecExternalItemType dataType = (isCertificate == JNI_TRUE ? kSecFormatX509Cert : kSecFormatWrappedPKCS8); + SecExternalFormat dataFormat = (isCertificate == JNI_TRUE ? kSecFormatX509Cert : kSecFormatWrappedPKCS8); // Convert the password obj into a CFStringRef that the keychain importer can use for encryption. SecKeyImportExportParameters paramBlock; @@ -533,7 +533,7 @@ paramBlock.keyUsage = CSSM_KEYUSE_ANY; paramBlock.keyAttributes = CSSM_KEYATTR_RETURN_DEFAULT; - err = SecKeychainItemImport(cfDataToImport, NULL, &dataType, NULL, + err = SecKeychainItemImport(cfDataToImport, NULL, &dataFormat, NULL, 0, ¶mBlock, defaultKeychain, &createdItems); if (err == noErr) { diff -r 7ecf45f5fa46 -r e77968f864eb src/java.base/share/classes/com/sun/crypto/provider/JceKeyStore.java --- a/src/java.base/share/classes/com/sun/crypto/provider/JceKeyStore.java Thu Sep 10 14:55:20 2015 -0700 +++ b/src/java.base/share/classes/com/sun/crypto/provider/JceKeyStore.java Tue Sep 15 07:47:44 2015 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2015, 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 @@ -864,7 +864,9 @@ if (computed[i] != actual[i]) { throw new IOException( "Keystore was tampered with, or " - + "password was incorrect"); + + "password was incorrect", + new UnrecoverableKeyException( + "Password verification failed")); } } } diff -r 7ecf45f5fa46 -r e77968f864eb src/java.base/share/classes/sun/security/pkcs12/PKCS12KeyStore.java --- a/src/java.base/share/classes/sun/security/pkcs12/PKCS12KeyStore.java Thu Sep 10 14:55:20 2015 -0700 +++ b/src/java.base/share/classes/sun/security/pkcs12/PKCS12KeyStore.java Tue Sep 15 07:47:44 2015 -0700 @@ -51,6 +51,8 @@ import java.util.*; import java.security.AlgorithmParameters; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; import javax.crypto.spec.PBEParameterSpec; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.SecretKeySpec; @@ -2060,7 +2062,7 @@ } if (!MessageDigest.isEqual(macData.getDigest(), macResult)) { - throw new SecurityException("Failed PKCS12" + + throw new UnrecoverableKeyException("Failed PKCS12" + " integrity checking"); } } catch (Exception e) { diff -r 7ecf45f5fa46 -r e77968f864eb src/java.base/share/classes/sun/util/cldr/CLDRLocaleProviderAdapter.java --- a/src/java.base/share/classes/sun/util/cldr/CLDRLocaleProviderAdapter.java Thu Sep 10 14:55:20 2015 -0700 +++ b/src/java.base/share/classes/sun/util/cldr/CLDRLocaleProviderAdapter.java Tue Sep 15 07:47:44 2015 -0700 @@ -41,6 +41,7 @@ import java.util.ServiceLoader; import java.util.Set; import java.util.StringTokenizer; +import java.util.stream.Stream; import sun.util.locale.provider.JRELocaleProviderAdapter; import sun.util.locale.provider.LocaleProviderAdapter; import sun.util.locale.provider.LocaleDataMetaInfo; @@ -148,11 +149,9 @@ private List applyParentLocales(String baseName, List candidates) { if (Objects.isNull(parentLocalesMap)) { Map map = new HashMap<>(); - Map parentLocales = baseMetaInfo.parentLocales(); - parentLocales.keySet().forEach(parent -> { - Arrays.asList(parentLocales.get(parent).split(" ")).stream().forEach(child -> { - map.put(Locale.forLanguageTag(child), - "root".equals(parent) ? Locale.ROOT : Locale.forLanguageTag(parent)); + baseMetaInfo.parentLocales().forEach((parent, children) -> { + Stream.of(children).forEach(child -> { + map.put(Locale.forLanguageTag(child), parent); }); }); parentLocalesMap = Collections.unmodifiableMap(map); diff -r 7ecf45f5fa46 -r e77968f864eb src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11KeyStore.java --- a/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11KeyStore.java Thu Sep 10 14:55:20 2015 -0700 +++ b/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11KeyStore.java Tue Sep 15 07:47:44 2015 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, 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 @@ -750,6 +750,21 @@ } else { login(new PasswordCallbackHandler(password)); } + } catch(LoginException e) { + Throwable cause = e.getCause(); + if (cause instanceof PKCS11Exception) { + PKCS11Exception pe = (PKCS11Exception) cause; + if (pe.getErrorCode() == CKR_PIN_INCORRECT) { + // if password is wrong, the cause of the IOException + // should be an UnrecoverableKeyException + throw new IOException("load failed", + new UnrecoverableKeyException().initCause(e)); + } + } + throw new IOException("load failed", e); + } + + try { if (mapLabels() == true) { // CKA_LABELs are shared by multiple certs writeDisabled = true; @@ -757,7 +772,7 @@ if (debug != null) { dumpTokenMap(); } - } catch (LoginException | KeyStoreException | PKCS11Exception e) { + } catch (KeyStoreException | PKCS11Exception e) { throw new IOException("load failed", e); } } diff -r 7ecf45f5fa46 -r e77968f864eb test/ProblemList.txt --- a/test/ProblemList.txt Thu Sep 10 14:55:20 2015 -0700 +++ b/test/ProblemList.txt Tue Sep 15 07:47:44 2015 -0700 @@ -133,9 +133,6 @@ # 8029891 java/lang/ClassLoader/deadlock/GetResource.java generic-all -# 8133552 -java/lang/ProcessHandle/InfoTest.java generic-all - ############################################################################ # jdk_instrument diff -r 7ecf45f5fa46 -r e77968f864eb test/java/lang/ProcessHandle/InfoTest.java --- a/test/java/lang/ProcessHandle/InfoTest.java Thu Sep 10 14:55:20 2015 -0700 +++ b/test/java/lang/ProcessHandle/InfoTest.java Tue Sep 15 07:47:44 2015 -0700 @@ -257,10 +257,15 @@ } } } - p1.waitFor(Utils.adjustTimeout(5), TimeUnit.SECONDS); + p1.sendAction("exit"); + Assert.assertTrue(p1.waitFor(Utils.adjustTimeout(30L), TimeUnit.SECONDS), + "timeout waiting for process to terminate"); } catch (IOException | InterruptedException ie) { ie.printStackTrace(System.out); Assert.fail("unexpected exception", ie); + } finally { + // Destroy any children that still exist + ProcessUtil.destroyProcessTree(ProcessHandle.current()); } } @@ -270,8 +275,9 @@ @Test public static void test3() { try { - for (int sleepTime : Arrays.asList(1, 2)) { + for (long sleepTime : Arrays.asList(Utils.adjustTimeout(30), Utils.adjustTimeout(32))) { Process p = spawn("sleep", String.valueOf(sleepTime)); + ProcessHandle.Info info = p.info(); System.out.printf(" info: %s%n", info); @@ -297,7 +303,9 @@ Assert.assertEquals(args[0], String.valueOf(sleepTime)); } } - Assert.assertTrue(p.waitFor(15, TimeUnit.SECONDS)); + p.destroy(); + Assert.assertTrue(p.waitFor(Utils.adjustTimeout(30), TimeUnit.SECONDS), + "timeout waiting for process to terminate"); } } catch (IOException | InterruptedException ex) { ex.printStackTrace(System.out); diff -r 7ecf45f5fa46 -r e77968f864eb test/java/security/KeyStore/TestKeyStoreBasic.java --- a/test/java/security/KeyStore/TestKeyStoreBasic.java Thu Sep 10 14:55:20 2015 -0700 +++ b/test/java/security/KeyStore/TestKeyStoreBasic.java Tue Sep 15 07:47:44 2015 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2015, 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 @@ -21,36 +21,97 @@ * questions. */ -import static java.lang.System.out; - +import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.InputStream; +import java.security.KeyFactory; import java.security.KeyStore; import java.security.KeyStoreException; -import java.security.Provider; -import java.security.Security; -import javax.crypto.SecretKey; -import javax.crypto.spec.SecretKeySpec; +import java.security.NoSuchProviderException; +import java.security.PrivateKey; +import java.security.UnrecoverableKeyException; +import java.security.cert.Certificate; +import java.security.cert.CertificateFactory; +import java.security.spec.KeySpec; +import java.security.spec.PKCS8EncodedKeySpec; +import java.util.Base64; /* * @test - * @bug 8048621 - * @summary Test the basic operations of KeyStore, provided by SunJCE (jceks), - * and SunPKCS11-Solaris(PKCS11KeyStore) + * @bug 8048621 8133090 + * @summary Test basic operations with keystores (jks, jceks, pkcs12) * @author Yu-Ching Valerie PENG */ +public class TestKeyStoreBasic { -public class TestKeyStoreBasic { + private static final String PRIVATE_KEY_PKCS8_BASE64 = "" + + "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCpyz97liuWPDYcLH9TX8BiT78o" + + "lCmAfmevvch6ncXUVuCzbdaKuKXwn4EVbDszsVJLoK5zdtP+X3iDhutj+IgKmLhuczF3M9VIcWr+" + + "JJUyTH4+3h/RT8cjCDZOmk9iXkb5ifruVsLqzb9g+Vp140Oz7leikne7KmclHvTfvFd0WDI7Gb9v" + + "o4f5rT717BXJ/n+M6pNk8DLpLiEu6eziYvXRv5x+t5Go3x0eCXdaxEQUf2j876Wfr2qHRJK7lDfF" + + "e1DDsMg/KpKGiILYZ+g2qtVMZSxtp5BZEtfB5qV/IE5kWO+mCIAGpXSZIdbERR6pZUq8GLEe1T9e" + + "+sO6H24w2F19AgMBAAECggEBAId/12187dO6wUPCjumuJA1QrrBnbKdKONyai36uoc1Od4s5QFj7" + + "+hEIeS7rbGNYQuBvnkgusAbzkW0FIpxpHce3EJez/emux6pEOKoP77BwMt9gy+txyu0+BHi91FQg" + + "AGvrnQDO5EYVY4Cz/WjOsJzKu8zVLg+DS0Toa2qRFwmUe9mVAXPNOCZ3Oae/Q6tCDsaINNw0fmjj" + + "jn6uohPbS+n6xENG3FkQXB36getXy310xTGED2J27cmAQH6gLR6Kl2iROzNPbbpBqbuemI9kbcld" + + "EwBS1jRfZWeaPstYA1niVrE9UgUBzemnoh4TDkG076sYthHMr5QFGjPswnwtJ4ECgYEA0sURQ5+v" + + "baH4tdaemI3qpnknXTlzSpuZZmAoyvY0Id0mlduwKwmZ3Y5989wHfnnhFfyNO4IkTKjI2Wp97qP5" + + "4eqUNpA7FtNU7KUzMcFDTtwtNZuRYMrKlqo2lLbA+gVrAYpYZFL4b7tcwtX4DnYorDsmude6W8sG" + + "4Mx2VdFJC9UCgYEAzjsdXCYH5doWUHb0dvn9ID7IikffEMRM720MRjrnnnVbpzx6ACntkPDNZg7p" + + "TRE/mx7iBz81ZaUWE+V0wd0JvCHEdpAz3mksyvDFhU4Bgs6xzf2pSul5muhsx3hHcvvPezz5Bnxs" + + "faJlzkxfwotyGmvWN15GA/pyfsZjsbbTpwkCgYAO6NnbysQCIV8SnegCKqfatt9N/O5m7LLhRxQb" + + "p2bwrlA4cZ34rWkw/w9x3LK7A6wkfgUPnJkswxPSLXJTG05l6M4rPfCwIKr1Qopojp9QSMr569NQ" + + "4YeLOOc7heIIzbFQHpU6I5Rncv2Q2sn9W+ZsqJKIuvX34FjQNiZ406EzMQKBgHSxOGS61D84DuZK" + + "2Ps1awhC3kB4eHzJRms3vflDPWoJJ+pSKwpKrzUTPHXiPBqyhtYkPGszVeiE6CAr9sv3YZnFVaBs" + + "6hyQUJsob+uE/w/gGvXe8VsFDx0bJOodYfhrCbTHBHWqE81nBcocpxayxsayfAzqWB3KKd0YLrMR" + + "K2PZAoGAcZa8915R2m0KZ6HVJUt/JDR85jCbN71kcVDFY2XSFkOJvOdFoHNfRckfLzjq9Y2MSSTV" + + "+QDWbDo2doUQCejJUTaN8nP79tfyir24X5uVPvQaeVoGTKYb+LfUqK0F60lStmjuddIGSZH55y3v" + + "+9XjmxbVERtd1lqgQg3VlmKlEXY="; + + /* + * Certificate: + * Data: + * Version: 3 (0x2) + * Serial Number: 7 (0x7) + * Signature Algorithm: sha512WithRSAEncryption + * Issuer: CN=Root + * Validity + * Not Before: Sep 1 18:03:59 2015 GMT + * Not After : Jan 17 18:03:59 2043 GMT + * Subject: CN=EE + */ + private static final String CERTIFICATE = "" + + "-----BEGIN CERTIFICATE-----\n" + + "MIIDHTCCAgWgAwIBAgIBBzANBgkqhkiG9w0BAQ0FADAPMQ0wCwYDVQQDDARSb290\n" + + "MB4XDTE1MDkwMTE4MDM1OVoXDTQzMDExNzE4MDM1OVowDTELMAkGA1UEAwwCRUUw\n" + + "ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCpyz97liuWPDYcLH9TX8Bi\n" + + "T78olCmAfmevvch6ncXUVuCzbdaKuKXwn4EVbDszsVJLoK5zdtP+X3iDhutj+IgK\n" + + "mLhuczF3M9VIcWr+JJUyTH4+3h/RT8cjCDZOmk9iXkb5ifruVsLqzb9g+Vp140Oz\n" + + "7leikne7KmclHvTfvFd0WDI7Gb9vo4f5rT717BXJ/n+M6pNk8DLpLiEu6eziYvXR\n" + + "v5x+t5Go3x0eCXdaxEQUf2j876Wfr2qHRJK7lDfFe1DDsMg/KpKGiILYZ+g2qtVM\n" + + "ZSxtp5BZEtfB5qV/IE5kWO+mCIAGpXSZIdbERR6pZUq8GLEe1T9e+sO6H24w2F19\n" + + "AgMBAAGjgYUwgYIwNAYDVR0fBC0wKzApoCegJYYjbGRhcDovL2xkYXAuaG9zdC5m\n" + + "b3IuY3JsZHAvbWFpbi5jcmwwSgYIKwYBBQUHAQEEPjA8MDoGCCsGAQUFBzAChi5s\n" + + "ZGFwOi8vbGRhcC5ob3N0LmZvci5haWEvZGM9Um9vdD9jQUNlcnRpZmljYXRlMA0G\n" + + "CSqGSIb3DQEBDQUAA4IBAQBWDfZHpuUx0yn5d3+BuztFqoks1MkGdk+USlH0TB1/\n" + + "gWWBd+4S4PCKlpSur0gj2rMW4fP5HQfNlHci8JV8/bG4KuKRAXW56dg1818Hl3pc\n" + + "iIrUSRn8uUjH3p9qb+Rb/u3mmVQRyJjN2t/zceNsO8/+Dd808OB9aEwGs8lMT0nn\n" + + "ZYaaAqYz1GIY/Ecyx1vfEZEQ1ljo6i/r70C3igbypBUShxSiGsleiVTLOGNA+MN1\n" + + "/a/Qh0bkaQyTGqK3bwvzzMeQVqWu2EWTBD/PmND5ExkpRICdv8LBVXfLnpoBr4lL\n" + + "hnxn9+e0Ah+t8dS5EKfn44w5bI5PCu2bqxs6RCTxNjcY\n" + + "-----END CERTIFICATE-----\n"; + private static final char[] PASSWD2 = new char[] { 'b', 'o', 'r', 'e', 'd' }; - private static final char[] PASSWDK = new String("cannot be null") + private static final char[] PASSWDK = "cannot be null" .toCharArray(); private static final String[] KS_Type = { "jks", "jceks", "pkcs12", "PKCS11KeyStore" }; - private static final String[] PRO_TYPE = { + private static final String[] PROVIDERS = { "SUN", "SunJCE", "SunJSSE", "SunPKCS11-Solaris" }; private static final String ALIAS_HEAD = "test"; @@ -61,41 +122,58 @@ } public void run() throws Exception { - Provider[] providers = Security.getProviders(); - for (Provider p: providers) { - String prvName = p.getName(); - if (prvName.startsWith("SunJCE") - || prvName.startsWith("SunPKCS11-Solaris")) { - try { - runTest(p); - out.println("Test with provider " + p.getName() + "" - + " passed"); - } catch (java.security.KeyStoreException e) { - if (prvName.startsWith("SunPKCS11-Solaris")) { - out.println("KeyStoreException is expected " - + "PKCS11KeyStore is invalid keystore type."); - e.printStackTrace(); - } else { - throw e; - } + for (String provider : PROVIDERS) { + try { + runTest(provider); + System.out.println("Test with provider " + provider + "passed"); + } catch (java.security.KeyStoreException e) { + if (provider.equals("SunPKCS11-Solaris")) { + System.out.println("KeyStoreException is expected: " + + "PKCS11KeyStore is invalid keystore type: " + e); + } else { + throw e; + } + } catch (NoSuchProviderException e) { + String osName = System.getProperty("os.name"); + if (provider.equals("SunPKCS11-Solaris") + && !osName.equals("SunOS")) { + System.out.println("Skip SunPKCS11-Solaris provider on " + + osName); + } else { + throw e; } } } } - public void runTest(Provider p) throws Exception { - SecretKey key = new SecretKeySpec( - new String("No one knows").getBytes(), "PBE"); + public void runTest(String provider) throws Exception { + + // load private key + // all keystore types should support private keys + KeySpec spec = new PKCS8EncodedKeySpec( + Base64.getMimeDecoder().decode(PRIVATE_KEY_PKCS8_BASE64)); + PrivateKey privateKey = KeyFactory.getInstance("RSA") + .generatePrivate(spec); + + // load x509 certificate + Certificate cert; + try (InputStream is = new BufferedInputStream( + new ByteArrayInputStream(CERTIFICATE.getBytes()))) { + cert = CertificateFactory.getInstance("X.509") + .generateCertificate(is); + } + int numEntries = 5; - String proName = p.getName(); String type = null; - for (int i = 0; i < PRO_TYPE.length; i++) { - if (proName.compareTo(PRO_TYPE[i]) == 0) { + for (int i = 0; i < PROVIDERS.length; i++) { + if (provider.compareTo(PROVIDERS[i]) == 0) { type = KS_Type[i]; break; } } - KeyStore ks = KeyStore.getInstance(type, p); + + System.out.printf("Test %s provider and %s keystore%n", provider, type); + KeyStore ks = KeyStore.getInstance(type, provider); KeyStore ks2 = KeyStore.getInstance(type, ks.getProvider().getName()); // create an empty key store @@ -103,7 +181,8 @@ // store the secret keys for (int j = 0; j < numEntries; j++) { - ks.setKeyEntry(ALIAS_HEAD + j, key, PASSWDK, null); + ks.setKeyEntry(ALIAS_HEAD + j, privateKey, PASSWDK, + new Certificate[] { cert }); } // initialize the 2nd key store object with the 1st one @@ -134,13 +213,18 @@ throw new RuntimeException( "ERROR: passed the loading with incorrect password"); } catch (IOException ex) { + System.out.println("Expected exception: " + ex); + if (!causedBy(ex, UnrecoverableKeyException.class)) { + ex.printStackTrace(System.out); + throw new RuntimeException("Unexpected cause"); + } + System.out.println("Expected cause: " + + UnrecoverableKeyException.class.getName()); + bais.reset(); ks.load(bais, PASSWD2); bais.reset(); ks.load(bais, null); - } finally { - bais.close(); - baos.close(); } // check key store type @@ -158,7 +242,6 @@ private void checkType(KeyStore obj, String type) { if (!obj.getType().equals(type)) { throw new RuntimeException("ERROR: wrong key store type"); - } } @@ -168,7 +251,6 @@ if (!obj.containsAlias(ALIAS_HEAD + k)) { throw new RuntimeException("ERROR: alias (" + k + ") should exist"); - } } } @@ -176,16 +258,25 @@ // compare the creation dates - true if all the same private void compareCreationDate(KeyStore o1, KeyStore o2, int range) throws KeyStoreException { - boolean result = true; - String alias = null; + String alias; for (int k = 0; k < range; k++) { alias = ALIAS_HEAD + k; if (!o1.getCreationDate(alias).equals(o2.getCreationDate(alias))) { throw new RuntimeException("ERROR: entry creation time (" + k + ") differs"); - } } } + // checks if an exception was caused by specified exception class + private static boolean causedBy(Exception e, Class klass) { + Throwable cause = e; + while ((cause = cause.getCause()) != null) { + if (cause.getClass().equals(klass)) { + return true; + } + } + return false; + } + } diff -r 7ecf45f5fa46 -r e77968f864eb test/java/security/cert/CertPathEncodingTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test/java/security/cert/CertPathEncodingTest.java Tue Sep 15 07:47:44 2015 -0700 @@ -0,0 +1,253 @@ +/* + * Copyright (c) 1998, 2015, 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. + */ +import java.io.ByteArrayInputStream; +import java.security.cert.CertPath; +import java.security.cert.Certificate; +import java.security.cert.CertificateFactory; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; + +/* + * @test + * @bug 8074931 + * @summary CertPathEncodingTest tests the ability of the CertPath and + * CertificateFactory to encode and decode CertPaths. + */ +public final class CertPathEncodingTest { + /* + Certificate: + Data: + Version: 3 (0x2) + Serial Number: 935438132 (0x37c1a734) + Signature Algorithm: dsaWithSHA1 + Issuer: C=us, O=sun, OU=east, OU=bcn, CN=yassir + Validity + Not Before: Aug 23 19:55:32 1999 GMT + Not After : Aug 22 19:55:32 2000 GMT + Subject: C=us, O=sun, OU=east, OU=bcn + Subject Public Key Info: + Public Key Algorithm: dsaEncryption + pub: + 63:47:4f:f6:29:e5:98:a2:21:fd:da:97:9e:3f:ca: + b0:17:49:8d:8a:a7:06:0d:a6:78:97:39:59:33:72: + a2:a5:74:d5:3a:ef:e6:7c:07:d7:8e:8e:d1:66:73: + 99:14:04:96:f5:31:d6:72:ee:d2:53:f8:90:b5:f3: + c3:f1:64:ba:1a:9e:c0:0a:da:92:48:c5:d3:84:7e: + 48:09:66:d9:51:ba:74:56:5a:77:8a:8c:9a:9c:f6: + 84:12:61:12:51:dc:c6:4f:84:94:ec:cb:78:51:83: + 8c:20:8a:53:7b:d2:b6:36:df:50:35:95:1f:cb:50: + 55:8b:3f:fb:e2:77:cb + P: + 00:fd:7f:53:81:1d:75:12:29:52:df:4a:9c:2e:ec: + e4:e7:f6:11:b7:52:3c:ef:44:00:c3:1e:3f:80:b6: + 51:26:69:45:5d:40:22:51:fb:59:3d:8d:58:fa:bf: + c5:f5:ba:30:f6:cb:9b:55:6c:d7:81:3b:80:1d:34: + 6f:f2:66:60:b7:6b:99:50:a5:a4:9f:9f:e8:04:7b: + 10:22:c2:4f:bb:a9:d7:fe:b7:c6:1b:f8:3b:57:e7: + c6:a8:a6:15:0f:04:fb:83:f6:d3:c5:1e:c3:02:35: + 54:13:5a:16:91:32:f6:75:f3:ae:2b:61:d7:2a:ef: + f2:22:03:19:9d:d1:48:01:c7 + Q: + 00:97:60:50:8f:15:23:0b:cc:b2:92:b9:82:a2:eb: + 84:0b:f0:58:1c:f5 + G: + 00:f7:e1:a0:85:d6:9b:3d:de:cb:bc:ab:5c:36:b8: + 57:b9:79:94:af:bb:fa:3a:ea:82:f9:57:4c:0b:3d: + 07:82:67:51:59:57:8e:ba:d4:59:4f:e6:71:07:10: + 81:80:b4:49:16:71:23:e8:4c:28:16:13:b7:cf:09: + 32:8c:c8:a6:e1:3c:16:7a:8b:54:7c:8d:28:e0:a3: + ae:1e:2b:b3:a6:75:91:6e:a3:7f:0b:fa:21:35:62: + f1:fb:62:7a:01:24:3b:cc:a4:f1:be:a8:51:90:89: + a8:83:df:e1:5a:e5:9f:06:92:8b:66:5e:80:7b:55: + 25:64:01:4c:3b:fe:cf:49:2a + X509v3 extensions: + X509v3 Key Usage: critical + Digital Signature, Key Encipherment, Certificate Sign + Signature Algorithm: dsaWithSHA1 + r: + 52:80:52:2b:2c:3d:02:66:58:b4:dc:ef:52:26:70: + 1b:53:ca:b3:7d + s: + 62:03:b2:ab:3e:18:2a:66:09:b6:ce:d4:05:a5:8e: + a5:7a:0d:55:67 + */ + private static final String cert1 = + "-----BEGIN CERTIFICATE-----\n" + + "MIICzTCCAougAwIBAgIEN8GnNDALBgcqhkjOOAQDBQAwSTELMAkGA1UEBhMCdXMx\n" + + "DDAKBgNVBAoTA3N1bjENMAsGA1UECxMEZWFzdDEMMAoGA1UECxMDYmNuMQ8wDQYD\n" + + "VQQDEwZ5YXNzaXIwHhcNOTkwODIzMTk1NTMyWhcNMDAwODIyMTk1NTMyWjA4MQsw\n" + + "CQYDVQQGEwJ1czEMMAoGA1UEChMDc3VuMQ0wCwYDVQQLEwRlYXN0MQwwCgYDVQQL\n" + + "EwNiY24wggG1MIIBLAYHKoZIzjgEATCCAR8CgYEA/X9TgR11EilS30qcLuzk5/YR\n" + + "t1I870QAwx4/gLZRJmlFXUAiUftZPY1Y+r/F9bow9subVWzXgTuAHTRv8mZgt2uZ\n" + + "UKWkn5/oBHsQIsJPu6nX/rfGG/g7V+fGqKYVDwT7g/bTxR7DAjVUE1oWkTL2dfOu\n" + + "K2HXKu/yIgMZndFIAccCFQCXYFCPFSMLzLKSuYKi64QL8Fgc9QKBgQD34aCF1ps9\n" + + "3su8q1w2uFe5eZSvu/o66oL5V0wLPQeCZ1FZV4661FlP5nEHEIGAtEkWcSPoTCgW\n" + + "E7fPCTKMyKbhPBZ6i1R8jSjgo64eK7OmdZFuo38L+iE1YvH7YnoBJDvMpPG+qFGQ\n" + + "iaiD3+Fa5Z8GkotmXoB7VSVkAUw7/s9JKgOBggACf2NHT/Yp5ZiiIf3al54/yrAX\n" + + "SY2KpwYNpniXOVkzcqKldNU67+Z8B9eOjtFmc5kUBJb1MdZy7tJT+JC188PxZLoa\n" + + "nsAK2pJIxdOEfkgJZtlRunRWWneKjJqc9oQSYRJR3MZPhJTsy3hRg4wgilN70rY2\n" + + "31A1lR/LUFWLP/vid8ujEzARMA8GA1UdDwEB/wQFAwMHpAAwCwYHKoZIzjgEAwUA\n" + + "Ay8AMCwCFFKAUissPQJmWLTc71ImcBtTyrN9AhRiA7KrPhgqZgm2ztQFpY6leg1V\n" + + "Zw==\n" + + "-----END CERTIFICATE-----\n" + + ""; + + /* + Certificate: + Data: + Version: 3 (0x2) + Serial Number: 935095671 (0x37bc6d77) + Signature Algorithm: dsaWithSHA1 + Issuer: C=us, O=sun, OU=east, OU=bcn, CN=yassir + Validity + Not Before: Aug 19 20:47:51 1999 GMT + Not After : Aug 18 20:47:51 2000 GMT + Subject: C=us, O=sun, OU=east, OU=bcn, CN=yassir + Subject Public Key Info: + Public Key Algorithm: dsaEncryption + pub: + 0a:cc:a4:ec:d6:88:45:c2:24:6b:0d:78:f1:82:f3: + 5e:3e:31:5d:fb:64:d5:06:5e:39:16:f1:0a:85:d1: + ff:d1:a4:74:c5:e6:b0:ba:93:1c:ee:69:51:be:3b: + a6:66:44:50:b4:f0:5e:0e:dd:9f:08:71:fe:a1:91: + 2e:d4:9e:6b:b2:c0:82:3c:91:6c:18:b0:d9:bc:a3: + 48:91:3f:8b:59:01:61:00:02:ab:22:31:bc:7c:6c: + 0d:9f:ed:be:33:e6:5c:44:9e:62:30:95:f8:6d:22: + d7:e5:85:4c:b0:98:6e:ad:cc:ca:3b:ad:cb:fa:f7: + 9f:37:13:f7:ca:e2:22:ba + P: + 00:fd:7f:53:81:1d:75:12:29:52:df:4a:9c:2e:ec: + e4:e7:f6:11:b7:52:3c:ef:44:00:c3:1e:3f:80:b6: + 51:26:69:45:5d:40:22:51:fb:59:3d:8d:58:fa:bf: + c5:f5:ba:30:f6:cb:9b:55:6c:d7:81:3b:80:1d:34: + 6f:f2:66:60:b7:6b:99:50:a5:a4:9f:9f:e8:04:7b: + 10:22:c2:4f:bb:a9:d7:fe:b7:c6:1b:f8:3b:57:e7: + c6:a8:a6:15:0f:04:fb:83:f6:d3:c5:1e:c3:02:35: + 54:13:5a:16:91:32:f6:75:f3:ae:2b:61:d7:2a:ef: + f2:22:03:19:9d:d1:48:01:c7 + Q: + 00:97:60:50:8f:15:23:0b:cc:b2:92:b9:82:a2:eb: + 84:0b:f0:58:1c:f5 + G: + 00:f7:e1:a0:85:d6:9b:3d:de:cb:bc:ab:5c:36:b8: + 57:b9:79:94:af:bb:fa:3a:ea:82:f9:57:4c:0b:3d: + 07:82:67:51:59:57:8e:ba:d4:59:4f:e6:71:07:10: + 81:80:b4:49:16:71:23:e8:4c:28:16:13:b7:cf:09: + 32:8c:c8:a6:e1:3c:16:7a:8b:54:7c:8d:28:e0:a3: + ae:1e:2b:b3:a6:75:91:6e:a3:7f:0b:fa:21:35:62: + f1:fb:62:7a:01:24:3b:cc:a4:f1:be:a8:51:90:89: + a8:83:df:e1:5a:e5:9f:06:92:8b:66:5e:80:7b:55: + 25:64:01:4c:3b:fe:cf:49:2a + X509v3 extensions: + X509v3 Key Usage: critical + Digital Signature, Key Encipherment, Certificate Sign + X509v3 Basic Constraints: critical + CA:TRUE, pathlen:5 + Signature Algorithm: dsaWithSHA1 + r: + 2f:88:46:37:94:92:b2:02:07:5b:8d:76:e5:81:23: + 85:7f:bc:8d:b9 + s: + 00:8b:d7:41:fa:11:c7:ab:27:92:5d:0a:03:98:56: + 36:42:5f:f5:1f:9d + */ + private static final String cert2 = + "-----BEGIN CERTIFICATE-----\n" + + "MIIC9TCCArKgAwIBAgIEN7xtdzALBgcqhkjOOAQDBQAwSTELMAkGA1UEBhMCdXMx\n" + + "DDAKBgNVBAoTA3N1bjENMAsGA1UECxMEZWFzdDEMMAoGA1UECxMDYmNuMQ8wDQYD\n" + + "VQQDEwZ5YXNzaXIwHhcNOTkwODE5MjA0NzUxWhcNMDAwODE4MjA0NzUxWjBJMQsw\n" + + "CQYDVQQGEwJ1czEMMAoGA1UEChMDc3VuMQ0wCwYDVQQLEwRlYXN0MQwwCgYDVQQL\n" + + "EwNiY24xDzANBgNVBAMTBnlhc3NpcjCCAbcwggEsBgcqhkjOOAQBMIIBHwKBgQD9\n" + + "f1OBHXUSKVLfSpwu7OTn9hG3UjzvRADDHj+AtlEmaUVdQCJR+1k9jVj6v8X1ujD2\n" + + "y5tVbNeBO4AdNG/yZmC3a5lQpaSfn+gEexAiwk+7qdf+t8Yb+DtX58aophUPBPuD\n" + + "9tPFHsMCNVQTWhaRMvZ1864rYdcq7/IiAxmd0UgBxwIVAJdgUI8VIwvMspK5gqLr\n" + + "hAvwWBz1AoGBAPfhoIXWmz3ey7yrXDa4V7l5lK+7+jrqgvlXTAs9B4JnUVlXjrrU\n" + + "WU/mcQcQgYC0SRZxI+hMKBYTt88JMozIpuE8FnqLVHyNKOCjrh4rs6Z1kW6jfwv6\n" + + "ITVi8ftiegEkO8yk8b6oUZCJqIPf4VrlnwaSi2ZegHtVJWQBTDv+z0kqA4GEAAKB\n" + + "gArMpOzWiEXCJGsNePGC814+MV37ZNUGXjkW8QqF0f/RpHTF5rC6kxzuaVG+O6Zm\n" + + "RFC08F4O3Z8Icf6hkS7UnmuywII8kWwYsNm8o0iRP4tZAWEAAqsiMbx8bA2f7b4z\n" + + "5lxEnmIwlfhtItflhUywmG6tzMo7rcv69583E/fK4iK6oycwJTAPBgNVHQ8BAf8E\n" + + "BQMDB6QAMBIGA1UdEwEB/wQIMAYBAf8CAQUwCwYHKoZIzjgEAwUAAzAAMC0CFC+I\n" + + "RjeUkrICB1uNduWBI4V/vI25AhUAi9dB+hHHqyeSXQoDmFY2Ql/1H50=\n" + + "-----END CERTIFICATE-----\n" + + ""; + + private static final String pkcs7path = + "MIIF9QYJKoZIhvcNAQcCoIIF5jCCBeICAQExADALBgkqhkiG9w0BBwGgggXKMIICzTCCAougAwIB\n" + + "AgIEN8GnNDALBgcqhkjOOAQDBQAwSTELMAkGA1UEBhMCdXMxDDAKBgNVBAoTA3N1bjENMAsGA1UE\n" + + "CxMEZWFzdDEMMAoGA1UECxMDYmNuMQ8wDQYDVQQDEwZ5YXNzaXIwHhcNOTkwODIzMTk1NTMyWhcN\n" + + "MDAwODIyMTk1NTMyWjA4MQswCQYDVQQGEwJ1czEMMAoGA1UEChMDc3VuMQ0wCwYDVQQLEwRlYXN0\n" + + "MQwwCgYDVQQLEwNiY24wggG1MIIBLAYHKoZIzjgEATCCAR8CgYEA/X9TgR11EilS30qcLuzk5/YR\n" + + "t1I870QAwx4/gLZRJmlFXUAiUftZPY1Y+r/F9bow9subVWzXgTuAHTRv8mZgt2uZUKWkn5/oBHsQ\n" + + "IsJPu6nX/rfGG/g7V+fGqKYVDwT7g/bTxR7DAjVUE1oWkTL2dfOuK2HXKu/yIgMZndFIAccCFQCX\n" + + "YFCPFSMLzLKSuYKi64QL8Fgc9QKBgQD34aCF1ps93su8q1w2uFe5eZSvu/o66oL5V0wLPQeCZ1FZ\n" + + "V4661FlP5nEHEIGAtEkWcSPoTCgWE7fPCTKMyKbhPBZ6i1R8jSjgo64eK7OmdZFuo38L+iE1YvH7\n" + + "YnoBJDvMpPG+qFGQiaiD3+Fa5Z8GkotmXoB7VSVkAUw7/s9JKgOBggACf2NHT/Yp5ZiiIf3al54/\n" + + "yrAXSY2KpwYNpniXOVkzcqKldNU67+Z8B9eOjtFmc5kUBJb1MdZy7tJT+JC188PxZLoansAK2pJI\n" + + "xdOEfkgJZtlRunRWWneKjJqc9oQSYRJR3MZPhJTsy3hRg4wgilN70rY231A1lR/LUFWLP/vid8uj\n" + + "EzARMA8GA1UdDwEB/wQFAwMHpAAwCwYHKoZIzjgEAwUAAy8AMCwCFFKAUissPQJmWLTc71ImcBtT\n" + + "yrN9AhRiA7KrPhgqZgm2ztQFpY6leg1VZzCCAvUwggKyoAMCAQICBDe8bXcwCwYHKoZIzjgEAwUA\n" + + "MEkxCzAJBgNVBAYTAnVzMQwwCgYDVQQKEwNzdW4xDTALBgNVBAsTBGVhc3QxDDAKBgNVBAsTA2Jj\n" + + "bjEPMA0GA1UEAxMGeWFzc2lyMB4XDTk5MDgxOTIwNDc1MVoXDTAwMDgxODIwNDc1MVowSTELMAkG\n" + + "A1UEBhMCdXMxDDAKBgNVBAoTA3N1bjENMAsGA1UECxMEZWFzdDEMMAoGA1UECxMDYmNuMQ8wDQYD\n" + + "VQQDEwZ5YXNzaXIwggG3MIIBLAYHKoZIzjgEATCCAR8CgYEA/X9TgR11EilS30qcLuzk5/YRt1I8\n" + + "70QAwx4/gLZRJmlFXUAiUftZPY1Y+r/F9bow9subVWzXgTuAHTRv8mZgt2uZUKWkn5/oBHsQIsJP\n" + + "u6nX/rfGG/g7V+fGqKYVDwT7g/bTxR7DAjVUE1oWkTL2dfOuK2HXKu/yIgMZndFIAccCFQCXYFCP\n" + + "FSMLzLKSuYKi64QL8Fgc9QKBgQD34aCF1ps93su8q1w2uFe5eZSvu/o66oL5V0wLPQeCZ1FZV466\n" + + "1FlP5nEHEIGAtEkWcSPoTCgWE7fPCTKMyKbhPBZ6i1R8jSjgo64eK7OmdZFuo38L+iE1YvH7YnoB\n" + + "JDvMpPG+qFGQiaiD3+Fa5Z8GkotmXoB7VSVkAUw7/s9JKgOBhAACgYAKzKTs1ohFwiRrDXjxgvNe\n" + + "PjFd+2TVBl45FvEKhdH/0aR0xeawupMc7mlRvjumZkRQtPBeDt2fCHH+oZEu1J5rssCCPJFsGLDZ\n" + + "vKNIkT+LWQFhAAKrIjG8fGwNn+2+M+ZcRJ5iMJX4bSLX5YVMsJhurczKO63L+vefNxP3yuIiuqMn\n" + + "MCUwDwYDVR0PAQH/BAUDAwekADASBgNVHRMBAf8ECDAGAQH/AgEFMAsGByqGSM44BAMFAAMwADAt\n" + + "AhQviEY3lJKyAgdbjXblgSOFf7yNuQIVAIvXQfoRx6snkl0KA5hWNkJf9R+dMQA=\n" + + ""; + + // Runs test of CertPath encoding and decoding. + public static void main(String[] args) throws Exception { + // Make the CertPath whose encoded form has already been stored + CertificateFactory certFac = CertificateFactory.getInstance("X509"); + + final List certs = new ArrayList<>(); + certs.add(certFac.generateCertificate(new ByteArrayInputStream(cert1.getBytes()))); + certs.add(certFac.generateCertificate(new ByteArrayInputStream(cert2.getBytes()))); + + CertPath cp = certFac.generateCertPath(certs); + + // Get the encoded form of the CertPath we made + byte[] encoded = cp.getEncoded("PKCS7"); + + // check if it matches the encoded value + if (!Arrays.equals(encoded, Base64.getMimeDecoder().decode(pkcs7path.getBytes()))) { + throw new RuntimeException("PKCS#7 encoding doesn't match stored value"); + } + + // Generate a CertPath from the encoded value and check if it equals + // the CertPath generated from the certificates + CertPath decodedCP = certFac.generateCertPath(new ByteArrayInputStream(encoded), "PKCS7"); + if (!decodedCP.equals(cp)) { + throw new RuntimeException("CertPath decoded from PKCS#7 isn't equal to original"); + } + } +} diff -r 7ecf45f5fa46 -r e77968f864eb test/java/security/cert/X509CertSelectorTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test/java/security/cert/X509CertSelectorTest.java Tue Sep 15 07:47:44 2015 -0700 @@ -0,0 +1,538 @@ +/* + * Copyright (c) 2000, 2015, 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. + */ +import static sun.security.x509.GeneralNameInterface.NAME_DIRECTORY; +import static sun.security.x509.NameConstraintsExtension.EXCLUDED_SUBTREES; +import static sun.security.x509.NameConstraintsExtension.PERMITTED_SUBTREES; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.math.BigInteger; +import java.security.GeneralSecurityException; +import java.security.KeyFactory; +import java.security.PublicKey; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509CertSelector; +import java.security.cert.X509Certificate; +import java.security.spec.X509EncodedKeySpec; +import java.util.Base64; +import java.util.Calendar; +import java.util.Date; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import sun.security.util.DerInputStream; +import sun.security.util.DerOutputStream; +import sun.security.util.DerValue; +import sun.security.util.ObjectIdentifier; +import sun.security.x509.AlgorithmId; +import sun.security.x509.AuthorityKeyIdentifierExtension; +import sun.security.x509.CertificatePoliciesExtension; +import sun.security.x509.DNSName; +import sun.security.x509.GeneralName; +import sun.security.x509.GeneralNameInterface; +import sun.security.x509.GeneralNames; +import sun.security.x509.GeneralSubtree; +import sun.security.x509.GeneralSubtrees; +import sun.security.x509.KeyIdentifier; +import sun.security.x509.NameConstraintsExtension; +import sun.security.x509.PolicyInformation; +import sun.security.x509.PrivateKeyUsageExtension; +import sun.security.x509.SubjectAlternativeNameExtension; +import sun.security.x509.X500Name; + +/* + * @test + * @bug 8074931 + * @summary This class tests the X509CertSelector. The tests check particular criteria + * by setting them to a value that should match our test certificate and + * ensuring that they do match, then setting them to a value that should not + * match our test certificate and ensuring that they do not match. + * @modules java.base/sun.security.x509 + * java.base/sun.security.util + */ +public class X509CertSelectorTest { + /* + Certificate: + Data: + Version: 3 (0x2) + Serial Number: 954172088 (0x38df82b8) + Signature Algorithm: dsaWithSHA1 + Issuer: C=us, O=sun, OU=testing + Validity + Not Before: Mar 27 15:48:08 2000 GMT + Not After : Jun 25 14:48:08 2000 GMT + Subject: C=us, O=sun, OU=testing, CN=mullan + Subject Public Key Info: + Public Key Algorithm: dsaEncryption + pub: 0 + P: 0 + Q: 0 + G: 0 + X509v3 extensions: + X509v3 Name Constraints: critical + 0D.B0@.>1.0...U....us1.0 + ..U. + ..sun1.0...U....testing1.0 + ..U....mullan + X509v3 Subject Key Identifier: + 56:E8:88:AE:9D:B5:3F:2B:CB:A0:4C:4B:E2:87:53:07:33:77:1B:DF + X509v3 Authority Key Identifier: + keyid:8E:DD:AF:6F:EE:02:12:F4:61:E9:2F:E3:64:1A:6F:71:32:25:20:C0 + + X509v3 Subject Alternative Name: + email:mullan@east.sun.com + X509v3 Private Key Usage Period: + Not Before: Jan 1 05:00:00 2000 GMT, Not After: Jan 1 05:00:00 2001 GMT + X509v3 Key Usage: critical + Digital Signature + X509v3 Certificate Policies: + 0$0\..*...0.0...+.......0.. + Testing... + Signature Algorithm: dsaWithSHA1 + r: + 44:c7:35:40:5d:6c:28:75:7f:73:b2:f8:0d:72:6c: + 09:65:b8:81:14 + s: + 76:79:f5:c7:37:3b:0d:9b:db:70:2f:20:80:36:e3: + 80:e8:a6:c6:71 + */ + private static final String testCert = + "-----BEGIN CERTIFICATE-----\n" + + "MIICLjCCAeygAwIBAgIEON+CuDALBgcqhkjOOAQDBQAwLTELMAkGA1UEBhMCdXMx\n" + + "DDAKBgNVBAoTA3N1bjEQMA4GA1UECxMHdGVzdGluZzAeFw0wMDAzMjcxNTQ4MDha\n" + + "Fw0wMDA2MjUxNDQ4MDhaMD4xCzAJBgNVBAYTAnVzMQwwCgYDVQQKEwNzdW4xEDAO\n" + + "BgNVBAsTB3Rlc3RpbmcxDzANBgNVBAMTBm11bGxhbjAcMBQGByqGSM44BAEwCQIB\n" + + "AAIBAAIBAAMEAAIBAKOCASMwggEfMFAGA1UdHgEB/wRGMESgQjBApD4xCzAJBgNV\n" + + "BAYTAnVzMQwwCgYDVQQKEwNzdW4xEDAOBgNVBAsTB3Rlc3RpbmcxDzANBgNVBAMT\n" + + "Bm11bGxhbjAdBgNVHQ4EFgQUVuiIrp21PyvLoExL4odTBzN3G98wHwYDVR0jBBgw\n" + + "FoAUjt2vb+4CEvRh6S/jZBpvcTIlIMAwHgYDVR0RBBcwFYETbXVsbGFuQGVhc3Qu\n" + + "c3VuLmNvbTArBgNVHRAEJDAigA8yMDAwMDEwMTA1MDAwMFqBDzIwMDEwMTAxMDUw\n" + + "MDAwWjAPBgNVHQ8BAf8EBQMDB4AAMC0GA1UdIAQmMCQwIgYEKoSAADAaMBgGCCsG\n" + + "AQUFBwICMAwSClRlc3RpbmcuLi4wCwYHKoZIzjgEAwUAAy8AMCwCFETHNUBdbCh1\n" + + "f3Oy+A1ybAlluIEUAhR2efXHNzsNm9twLyCANuOA6KbGcQ==\n" + + "-----END CERTIFICATE-----\n" + + ""; + + private static final String testKey = + "MIIBtjCCASsGByqGSM44BAEwggEeAoGBAIVWPEkcxbxhQRCqVzg55tNqbP5j0K4kdu4bkmXvfqC5\n" + + "+qA75DvnfzsOJseb+9AuKXWk/DvCzFDmrY1YaU3scZC3OQEO9lEO3F4VDKOaudY6OT1SI22pAIwz\n" + + "j5pvq+i7zOp4xUqkQUeh/4iQSfxOT5UrFGjkcbnbpVkCXD/GxAz7AhUAjtnm3dVIddUUHl6wxpZ7\n" + + "GcA6gSsCgYAf/PXzQtemgIDjpFrNNSgTEKkLposBXKatAM+gUKlMUjf8SQvquqPxDtRrscGjXkoL\n" + + "oTkaR7/akULYFpBvUcFkeIFiCnJg8M9XhCWdLvn9MPt+jR2oxookvCb9xLtD6WvIM/wd/nZ1iK4u\n" + + "iY1+q85xvns/Awbtwl7oZDAwE2TUKAOBhAACgYBDc9UZ+3xsZubUZvRG5cpyJceYpJp2exOPVJXn\n" + + "jR4CcR+cT9bAJpFSxqE/8KtNHXxHdu4f3DU67IMOVDpugzihyzXJvNm3w2H9x+6xczHG2wjvAJeh\n" + + "X62EWbUatxPXFAoVKZWuUbaYaZzdWBDtNRrCuKKsLo0GFy8g2BZISuD3jw==\n" + + ""; + + // Certificate to run tests on + private final X509Certificate cert; + + public static void main(String[] args) throws Exception { + X509CertSelectorTest test = new X509CertSelectorTest(); + test.doTest(); + } + + public X509CertSelectorTest() throws CertificateException, IOException { + cert = (X509Certificate) CertificateFactory.getInstance("X.509") + .generateCertificate(new ByteArrayInputStream(testCert.getBytes())); + } + + // Runs the test. + private void doTest() throws Exception { + System.out.println("START OF TESTS FOR " + "X509CertSelector"); + + testSerialNumber(); + testIssuer(); + testSubjectKeyIdentifier(); + testAuthorityKeyIdentifier(); + testCertificateValid(); + testPrivateKeyValid(); + testSubjectPublicKeyAlgID(); + testKeyUsage(); + testSubjectAltName(); + testPolicy(); + testPathToName(); + testSubject(); + testSubjectPublicKey(); + testNameConstraints(); + testBasicConstraints(); + testCertificate(); + } + + // Tests matching on the serial number contained in the certificate. + private void testSerialNumber() { + System.out.println("X.509 Certificate Match on serialNumber"); + // bad match + X509CertSelector selector = new X509CertSelector(); + selector.setSerialNumber(new BigInteger("999999999")); + checkMatch(selector, cert, false); + + // good match + selector.setSerialNumber(cert.getSerialNumber()); + checkMatch(selector, cert, true); + } + + // Tests matching on the issuer name contained in the certificate. + private void testIssuer() throws IOException { + System.out.println("X.509 Certificate Match on issuer"); + // bad match + X509CertSelector selector = new X509CertSelector(); + selector.setIssuer("ou=bogus,ou=east,o=sun,c=us"); + checkMatch(selector, cert, false); + + // good match + selector.setIssuer((cert.getIssuerX500Principal()).getName("RFC2253")); + checkMatch(selector, cert, true); + } + + /* + * Tests matching on the subject key identifier contained in the + * certificate. + */ + private void testSubjectKeyIdentifier() throws IOException { + System.out.println("X.509 Certificate Match on subjectKeyIdentifier"); + // bad match + X509CertSelector selector = new X509CertSelector(); + byte[] b = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; + selector.setSubjectKeyIdentifier(b); + checkMatch(selector, cert, false); + + // good match + DerInputStream in = new DerInputStream(cert.getExtensionValue("2.5.29.14")); + byte[] encoded = in.getOctetString(); + selector.setSubjectKeyIdentifier(encoded); + checkMatch(selector, cert, true); + } + + /* + * Tests matching on the authority key identifier contained in the + * certificate. + */ + private void testAuthorityKeyIdentifier() throws IOException { + System.out.println("X.509 Certificate Match on authorityKeyIdentifier"); + // bad match + X509CertSelector selector = new X509CertSelector(); + byte[] b = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; + AuthorityKeyIdentifierExtension a = new AuthorityKeyIdentifierExtension(new KeyIdentifier(b), null, null); + selector.setAuthorityKeyIdentifier(a.getExtensionValue()); + checkMatch(selector, cert, false); + + // good match + DerInputStream in = new DerInputStream(cert.getExtensionValue("2.5.29.35")); + byte[] encoded = in.getOctetString(); + selector.setAuthorityKeyIdentifier(encoded); + checkMatch(selector, cert, true); + } + + /* + * Tests matching on the certificate validity component contained in the + * certificate. + */ + private void testCertificateValid() { + System.out.println("X.509 Certificate Match on certificateValid"); + // bad match + X509CertSelector selector = new X509CertSelector(); + Calendar cal = Calendar.getInstance(); + cal.set(1968, 12, 31); + selector.setCertificateValid(cal.getTime()); + checkMatch(selector, cert, false); + + // good match + selector.setCertificateValid(cert.getNotBefore()); + checkMatch(selector, cert, true); + } + + /* + * Tests matching on the private key validity component contained in the + * certificate. + */ + private void testPrivateKeyValid() throws IOException, CertificateException { + System.out.println("X.509 Certificate Match on privateKeyValid"); + // bad match + X509CertSelector selector = new X509CertSelector(); + Calendar cal = Calendar.getInstance(); + cal.set(1968, 12, 31); + selector.setPrivateKeyValid(cal.getTime()); + checkMatch(selector, cert, false); + + // good match + DerInputStream in = new DerInputStream(cert.getExtensionValue("2.5.29.16")); + byte[] encoded = in.getOctetString(); + PrivateKeyUsageExtension ext = new PrivateKeyUsageExtension(false, encoded); + Date validDate = (Date) ext.get(PrivateKeyUsageExtension.NOT_BEFORE); + selector.setPrivateKeyValid(validDate); + checkMatch(selector, cert, true); + + } + + private ObjectIdentifier getCertPubKeyAlgOID(X509Certificate xcert) throws IOException { + byte[] encodedKey = xcert.getPublicKey().getEncoded(); + DerValue val = new DerValue(encodedKey); + if (val.tag != DerValue.tag_Sequence) { + throw new RuntimeException("invalid key format"); + } + + return AlgorithmId.parse(val.data.getDerValue()).getOID(); + } + + /* + * Tests matching on the subject public key algorithm ID component contained + * in the certificate. + */ + private void testSubjectPublicKeyAlgID() throws IOException { + System.out.println("X.509 Certificate Match on subjectPublicKeyAlgID"); + // bad match + X509CertSelector selector = new X509CertSelector(); + selector.setSubjectPublicKeyAlgID("2.5.29.14"); + checkMatch(selector, cert, false); + + // good match + selector.setSubjectPublicKeyAlgID(getCertPubKeyAlgOID(cert).toString()); + checkMatch(selector, cert, true); + + } + + // Tests matching on the key usage extension contained in the certificate. + private void testKeyUsage() { + System.out.println("X.509 Certificate Match on keyUsage"); + // bad match + X509CertSelector selector = new X509CertSelector(); + boolean[] keyUsage = { true, false, true, false, true, false, true, false }; + selector.setKeyUsage(keyUsage); + System.out.println("Selector = " + selector.toString()); + checkMatch(selector, cert, false); + + // good match + selector.setKeyUsage(cert.getKeyUsage()); + System.out.println("Selector = " + selector.toString()); + checkMatch(selector, cert, true); + } + + /* + * Tests matching on the subject alternative name extension contained in the + * certificate. + */ + private void testSubjectAltName() throws IOException { + System.out.println("X.509 Certificate Match on subjectAltName"); + // bad match + X509CertSelector selector = new X509CertSelector(); + GeneralNameInterface dnsName = new DNSName("foo.com"); + DerOutputStream tmp = new DerOutputStream(); + dnsName.encode(tmp); + selector.addSubjectAlternativeName(2, tmp.toByteArray()); + checkMatch(selector, cert, false); + + // good match + DerInputStream in = new DerInputStream(cert.getExtensionValue("2.5.29.17")); + byte[] encoded = in.getOctetString(); + SubjectAlternativeNameExtension ext = new SubjectAlternativeNameExtension(false, encoded); + GeneralNames names = (GeneralNames) ext.get(SubjectAlternativeNameExtension.SUBJECT_NAME); + GeneralName name = (GeneralName) names.get(0); + selector.setSubjectAlternativeNames(null); + DerOutputStream tmp2 = new DerOutputStream(); + name.getName().encode(tmp2); + selector.addSubjectAlternativeName(name.getType(), tmp2.toByteArray()); + checkMatch(selector, cert, true); + + // good match 2 (matches at least one) + selector.setMatchAllSubjectAltNames(false); + selector.addSubjectAlternativeName(2, "foo.com"); + checkMatch(selector, cert, true); + } + + /* + * Tests matching on the policy constraints extension contained in the + * certificate. + */ + private void testPolicy() throws IOException { + System.out.println("X.509 Certificate Match on certificatePolicies"); + // test encoding of CertificatePoliciesExtension because we wrote the + // code + // bad match + X509CertSelector selector = new X509CertSelector(); + Set s = new HashSet<>(); + s.add(new String("1.2.5.7.68")); + selector.setPolicy(s); + checkMatch(selector, cert, false); + + // good match + DerInputStream in = new DerInputStream(cert.getExtensionValue("2.5.29.32")); + CertificatePoliciesExtension ext = new CertificatePoliciesExtension(false, in.getOctetString()); + List policies = ext.get(CertificatePoliciesExtension.POLICIES); + // match on the first policy id + PolicyInformation policyInfo = (PolicyInformation) policies.get(0); + s.clear(); + s.add(policyInfo.getPolicyIdentifier().getIdentifier().toString()); + selector.setPolicy(s); + checkMatch(selector, cert, true); + } + + /* + * Tests matching on the name constraints extension contained in the + * certificate. + */ + private void testPathToName() throws IOException { + System.out.println("X.509 Certificate Match on pathToName"); + + X509CertSelector selector = null; + DerInputStream in = new DerInputStream(cert.getExtensionValue("2.5.29.30")); + byte[] encoded = in.getOctetString(); + NameConstraintsExtension ext = new NameConstraintsExtension(false, encoded); + GeneralSubtrees permitted = (GeneralSubtrees) ext.get(PERMITTED_SUBTREES); + GeneralSubtrees excluded = (GeneralSubtrees) ext.get(EXCLUDED_SUBTREES); + + // bad matches on pathToName within excluded subtrees + if (excluded != null) { + Iterator e = excluded.iterator(); + while (e.hasNext()) { + GeneralSubtree tree = e.next(); + if (tree.getName().getType() == NAME_DIRECTORY) { + X500Name excludedDN1 = new X500Name(tree.getName().toString()); + X500Name excludedDN2 = new X500Name("CN=Bogus, " + tree.getName().toString()); + DerOutputStream derDN1 = new DerOutputStream(); + DerOutputStream derDN2 = new DerOutputStream(); + excludedDN1.encode(derDN1); + excludedDN2.encode(derDN2); + selector = new X509CertSelector(); + selector.addPathToName(NAME_DIRECTORY, derDN1.toByteArray()); + checkMatch(selector, cert, false); + selector.setPathToNames(null); + selector.addPathToName(NAME_DIRECTORY, derDN2.toByteArray()); + checkMatch(selector, cert, false); + } + } + } + + // good matches on pathToName within permitted subtrees + if (permitted != null) { + Iterator e = permitted.iterator(); + while (e.hasNext()) { + GeneralSubtree tree = e.next(); + if (tree.getName().getType() == NAME_DIRECTORY) { + X500Name permittedDN1 = new X500Name(tree.getName().toString()); + X500Name permittedDN2 = new X500Name("CN=good, " + tree.getName().toString()); + DerOutputStream derDN1 = new DerOutputStream(); + DerOutputStream derDN2 = new DerOutputStream(); + permittedDN1.encode(derDN1); + permittedDN2.encode(derDN2); + selector = new X509CertSelector(); + selector.addPathToName(NAME_DIRECTORY, derDN1.toByteArray()); + checkMatch(selector, cert, true); + selector.setPathToNames(null); + selector.addPathToName(NAME_DIRECTORY, derDN2.toByteArray()); + checkMatch(selector, cert, true); + } + } + } + } + + // Tests matching on the subject name contained in the certificate. + private void testSubject() throws IOException { + System.out.println("X.509 Certificate Match on subject"); + // bad match + X509CertSelector selector = new X509CertSelector(); + selector.setSubject("ou=bogus,ou=east,o=sun,c=us"); + checkMatch(selector, cert, false); + + // good match + selector.setSubject(cert.getSubjectX500Principal().getName("RFC2253")); + checkMatch(selector, cert, true); + } + + // Tests matching on the subject public key contained in the certificate. + private void testSubjectPublicKey() throws IOException, GeneralSecurityException { + System.out.println("X.509 Certificate Match on subject public key"); + // bad match + X509CertSelector selector = new X509CertSelector(); + X509EncodedKeySpec keySpec = new X509EncodedKeySpec( + Base64.getMimeDecoder().decode(testKey.getBytes())); + KeyFactory keyFactory = KeyFactory.getInstance("DSA"); + PublicKey pubKey = keyFactory.generatePublic(keySpec); + selector.setSubjectPublicKey(pubKey); + checkMatch(selector, cert, false); + + // good match + selector.setSubjectPublicKey(cert.getPublicKey()); + checkMatch(selector, cert, true); + } + + // Tests matching on the name constraints contained in the certificate. + private void testNameConstraints() throws IOException { + System.out.println("X.509 Certificate Match on name constraints"); + // bad match + GeneralSubtrees subjectTree = new GeneralSubtrees(); + subjectTree.add(getGeneralSubtree((X500Name) cert.getSubjectDN())); + NameConstraintsExtension ext = new NameConstraintsExtension((GeneralSubtrees) null, subjectTree); + X509CertSelector selector = new X509CertSelector(); + selector.setNameConstraints(ext.getExtensionValue()); + checkMatch(selector, cert, false); + + // good match + ext = new NameConstraintsExtension(subjectTree, null); + selector.setNameConstraints(ext.getExtensionValue()); + checkMatch(selector, cert, true); + } + + // Tests matching on basic constraints. + private void testBasicConstraints() { + System.out.println("X.509 Certificate Match on basic constraints"); + // bad match + X509CertSelector selector = new X509CertSelector(); + int mpl = cert.getBasicConstraints(); + selector.setBasicConstraints(0); + checkMatch(selector, cert, false); + + // good match + selector.setBasicConstraints(mpl); + checkMatch(selector, cert, true); + } + + // Tests certificateEquals criterion + private void testCertificate() { + System.out.println("X.509 Certificate Match on certificateEquals criterion"); + + X509CertSelector selector = new X509CertSelector(); + // good match + selector.setCertificate(cert); + checkMatch(selector, cert, true); + } + + private void checkMatch(X509CertSelector selector, X509Certificate cert, boolean match) { + boolean result = selector.match(cert); + if (match != result) + throw new RuntimeException(selector + " match " + cert + " is " + result + ", but expect " + match); + } + + private static GeneralSubtree getGeneralSubtree(GeneralNameInterface gni) { + // Create a new GeneralSubtree with the specified name, 0 base, and + // unlimited length + GeneralName gn = new GeneralName(gni); + GeneralSubtree subTree = new GeneralSubtree(gn, 0, -1); + return subTree; + } +} diff -r 7ecf45f5fa46 -r e77968f864eb test/sun/security/krb5/auto/KrbTicket.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test/sun/security/krb5/auto/KrbTicket.java Tue Sep 15 07:47:44 2015 -0700 @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2015, 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. + */ + +import java.nio.file.Files; +import java.nio.file.Paths; +import java.time.Instant; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import javax.security.auth.RefreshFailedException; +import javax.security.auth.Subject; +import javax.security.auth.kerberos.KerberosTicket; +import javax.security.auth.login.LoginContext; + +/* + * @test + * @bug 6857795 8075299 + * @summary Checks Kerberos ticket properties + * @run main/othervm KrbTicket + */ +public class KrbTicket { + + private static final String REALM = "TEST.REALM"; + private static final String HOST = "localhost"; + private static final String USER = "TESTER"; + private static final String USER_PRINCIPAL = USER + "@" + REALM; + private static final String PASSWORD = "password"; + private static final String KRBTGT_PRINCIPAL = "krbtgt/" + REALM; + private static final String KRB5_CONF_FILENAME = "krb5.conf"; + private static final String JAAS_CONF = "jaas.conf"; + private static final long TICKET_LIFTETIME = 5 * 60 * 1000; // 5 mins + + public static void main(String[] args) throws Exception { + // define principals + Map principals = new HashMap<>(); + principals.put(USER_PRINCIPAL, PASSWORD); + principals.put(KRBTGT_PRINCIPAL, null); + + System.setProperty("java.security.krb5.conf", KRB5_CONF_FILENAME); + + // start a local KDC instance + KDC kdc = KDC.startKDC(HOST, null, REALM, principals, null, null); + KDC.saveConfig(KRB5_CONF_FILENAME, kdc, + "forwardable = true", "proxiable = true"); + + // create JAAS config + Files.write(Paths.get(JAAS_CONF), Arrays.asList( + "Client {", + " com.sun.security.auth.module.Krb5LoginModule required;", + "};" + )); + System.setProperty("java.security.auth.login.config", JAAS_CONF); + System.setProperty("javax.security.auth.useSubjectCredsOnly", "false"); + + long startTime = Instant.now().getEpochSecond() * 1000; + + LoginContext lc = new LoginContext("Client", + new Helper.UserPasswordHandler(USER, PASSWORD)); + lc.login(); + + Subject subject = lc.getSubject(); + System.out.println("subject: " + subject); + + Set creds = subject.getPrivateCredentials( + KerberosTicket.class); + + if (creds.size() > 1) { + throw new RuntimeException("Multiple credintials found"); + } + + Object o = creds.iterator().next(); + if (!(o instanceof KerberosTicket)) { + throw new RuntimeException("Instance of KerberosTicket expected"); + } + KerberosTicket krbTkt = (KerberosTicket) o; + + System.out.println("forwardable = " + krbTkt.isForwardable()); + System.out.println("proxiable = " + krbTkt.isProxiable()); + System.out.println("renewable = " + krbTkt.isRenewable()); + System.out.println("current = " + krbTkt.isCurrent()); + + if (!krbTkt.isForwardable()) { + throw new RuntimeException("Forwardable ticket expected"); + } + + if (!krbTkt.isProxiable()) { + throw new RuntimeException("Proxiable ticket expected"); + } + + if (!krbTkt.isCurrent()) { + throw new RuntimeException("Ticket is not current"); + } + + if (krbTkt.isRenewable()) { + throw new RuntimeException("Not renewable ticket expected"); + } + try { + krbTkt.refresh(); + throw new RuntimeException( + "Expected RefreshFailedException not thrown"); + } catch(RefreshFailedException e) { + System.out.println("Expected exception: " + e); + } + + if (!checkTime(krbTkt, startTime)) { + throw new RuntimeException("Wrong ticket life time"); + } + + krbTkt.destroy(); + if (!krbTkt.isDestroyed()) { + throw new RuntimeException("Ticket not destroyed"); + } + + System.out.println("Test passed"); + } + + private static boolean checkTime(KerberosTicket krbTkt, long startTime) { + long ticketEndTime = krbTkt.getEndTime().getTime(); + long roughLifeTime = ticketEndTime - startTime; + System.out.println("start time = " + startTime); + System.out.println("end time = " + ticketEndTime); + System.out.println("rough life time = " + roughLifeTime); + return roughLifeTime >= TICKET_LIFTETIME; + } +} diff -r 7ecf45f5fa46 -r e77968f864eb test/sun/security/krb5/auto/tools/KinitConfPlusProps.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test/sun/security/krb5/auto/tools/KinitConfPlusProps.java Tue Sep 15 07:47:44 2015 -0700 @@ -0,0 +1,188 @@ +/* + * Copyright (c) 2015, 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. + */ + +import java.io.File; +import java.net.PortUnreachableException; +import java.util.HashMap; +import java.util.Map; +import jdk.testlibrary.ProcessTools; +import jdk.testlibrary.OutputAnalyzer; + +/* + * @test + * @bug 6857795 8075299 + * @summary Checks if kinit uses both krb5 conf file and system properties + * @requires os.family == "windows" + * @library /lib/testlibrary + * @library /sun/security/krb5/auto + * @run main/othervm KinitConfPlusProps + */ +public class KinitConfPlusProps { + + private static final String KINIT = System.getProperty("java.home") + + File.separator + "bin" + File.separator + "kinit"; + private static final String KLIST = System.getProperty("java.home") + + File.separator + "bin" + File.separator + "klist"; + private static final String REALM = "REALM"; + private static final String ANOTHER_REALM = "ANOTHER.REALM"; + private static final String HOST = "localhost"; + private static final String CC_FILENAME = "krb5cc_test"; + private static final String USER = "TESTER"; + private static final String USER_PRINCIPAL = USER + "@" + REALM; + private static final String KRBTGT_PRINCIPAL = "krbtgt/" + REALM; + private static final String KEYTAB_FILE = "test.keytab"; + private static final String KRB5_CONF_FILENAME = "krb5.conf"; + + public static void main(String[] args) throws Exception { + // define principals + Map principals = new HashMap<>(); + principals.put(USER_PRINCIPAL, null); + principals.put(KRBTGT_PRINCIPAL, null); + + System.setProperty("java.security.krb5.conf", KRB5_CONF_FILENAME); + + // start a local KDC instance + KDC kdc = KDC.startKDC(HOST, null, REALM, principals, KEYTAB_FILE, + KDC.KtabMode.APPEND); + KDC.saveConfig(KRB5_CONF_FILENAME, kdc, + "forwardable = true", "proxiable = true"); + + boolean success = true; + + /* + * kinit should fail since java.security.krb5.kdc + * and java.security.krb5.realm properties override correct values + * in krb5 conf file + */ + String[] command = {KINIT, "-k", + "-J-Djava.security.krb5.realm=" + REALM, + "-J-Djava.security.krb5.kdc=" + HOST, // without port + "-J-Djava.security.krb5.conf=" + KRB5_CONF_FILENAME, + "-t", KEYTAB_FILE, + "-c", CC_FILENAME, + USER + }; + + try { + OutputAnalyzer out = ProcessTools.executeCommand(command); + out.shouldHaveExitValue(-1); + out.shouldContain(PortUnreachableException.class.getName()); + } catch(Throwable e) { + System.out.println("Unexpected exception: " + e); + e.printStackTrace(System.out); + success = false; + } + + /* + * kinit should succeed + * since realm should be picked up from principal name + */ + command = new String[] {KINIT, "-k", + "-J-Djava.security.krb5.realm=" + ANOTHER_REALM, + "-J-Djava.security.krb5.kdc=" + HOST, + "-J-Djava.security.krb5.conf=" + KRB5_CONF_FILENAME, + "-t", KEYTAB_FILE, + "-c", CC_FILENAME, + USER_PRINCIPAL + }; + + try { + OutputAnalyzer out = ProcessTools.executeCommand(command); + out.shouldHaveExitValue(0); + out.shouldContain(CC_FILENAME); + } catch(Throwable e) { + System.out.println("Unexpected exception: " + e); + e.printStackTrace(System.out); + success = false; + } + + success &= checkTicketFlags(); + + /* + * kinit should succeed + * since realm should be picked up from principal name, + * and other data should come from krb5 conf file + */ + command = new String[] {KINIT, "-k", + "-J-Djava.security.krb5.conf=" + KRB5_CONF_FILENAME, + "-t", KEYTAB_FILE, + "-c", CC_FILENAME, + USER_PRINCIPAL + }; + + try { + OutputAnalyzer out = ProcessTools.executeCommand(command); + out.shouldHaveExitValue(0); + out.shouldContain(CC_FILENAME); + } catch(Throwable e) { + System.out.println("Unexpected exception: " + e); + e.printStackTrace(System.out); + success = false; + } + + success &= checkTicketFlags(); + + // kinit should succeed even if a principal name doesn't have realm + command = new String[] {KINIT, "-k", + "-J-Djava.security.krb5.conf=" + KRB5_CONF_FILENAME, + "-t", KEYTAB_FILE, + "-c", CC_FILENAME, + USER + }; + + try { + OutputAnalyzer out = ProcessTools.executeCommand(command); + out.shouldHaveExitValue(0); + out.shouldContain(CC_FILENAME); + } catch(Throwable e) { + System.out.println("Unexpected exception: " + e); + e.printStackTrace(System.out); + success = false; + } + + success &= checkTicketFlags(); + + if (!success) { + throw new RuntimeException("At least one test case failed"); + } + System.out.println("Test passed"); + } + + // check if a ticket has forwardable and proxiable flags + private static boolean checkTicketFlags() { + String[] command = new String[] {KLIST, "-f", "-c", CC_FILENAME}; + + try { + OutputAnalyzer out = ProcessTools.executeCommand(command); + out.shouldHaveExitValue(0); + out.shouldContain("FORWARDABLE"); + out.shouldContain("PROXIABLE"); + } catch(Throwable e) { + System.out.println("Unexpected exception: " + e); + e.printStackTrace(System.out); + return false; + } + + return true; + } +} diff -r 7ecf45f5fa46 -r e77968f864eb test/sun/security/pkcs11/PKCS11Test.java --- a/test/sun/security/pkcs11/PKCS11Test.java Thu Sep 10 14:55:20 2015 -0700 +++ b/test/sun/security/pkcs11/PKCS11Test.java Tue Sep 15 07:47:44 2015 -0700 @@ -33,6 +33,8 @@ public abstract class PKCS11Test { + static final String PKCS11 = "PKCS11"; + // directory of the test source static final String BASE = System.getProperty("test.src", "."); @@ -644,4 +646,12 @@ return ""; } } + + static byte[] generateData(int length) { + byte data[] = new byte[length]; + for (int i=0; i entries = new ArrayList(); - for (String alias : Collections.list(jks.aliases())) { - if (jks.entryInstanceOf(alias, PrivateKeyEntry.class)) { - PrivateKeyEntry entry = (PrivateKeyEntry)jks.getEntry(alias, new PasswordProtection(jkspass)); - String algorithm = entry.getPrivateKey().getAlgorithm(); - System.out.println("-Entry " + alias + " (" + algorithm + ")"); - if ((supportsEC == false) && algorithm.equals("EC")) { - System.out.println("EC not supported by provider, skipping"); - continue; - } - if ((supportsEC == false) && algorithm.equals("DSA")) { - System.out.println("Provider does not appear to have CKA_NETSCAPE_DB fix, skipping"); - continue; - } - test(p, entry); - } // else ignore + try (InputStream in = new FileInputStream(BASE + SEP + "keystore.jks")) { + char[] jkspass = "passphrase".toCharArray(); + jks.load(in, jkspass); + for (String alias : Collections.list(jks.aliases())) { + if (jks.entryInstanceOf(alias, PrivateKeyEntry.class)) { + PrivateKeyEntry entry = (PrivateKeyEntry)jks.getEntry(alias, + new PasswordProtection(jkspass)); + String algorithm = entry.getPrivateKey().getAlgorithm(); + System.out.printf("-Entry %s (%s)%n", alias, algorithm); + if ((supportsEC == false) && algorithm.equals("EC")) { + System.out.println("EC not supported by provider, " + + "skipping"); + continue; + } + if ((supportsEC == false) && algorithm.equals("DSA")) { + System.out.println("Provider does not appear to have " + + "CKA_NETSCAPE_DB fix, skipping"); + continue; + } + test(p, entry); + } // else ignore + } } System.out.println("OK"); } @@ -92,10 +101,6 @@ return Collections.list(ks.aliases()); } - private final static String ALIAS1 = "entry1"; - private final static String ALIAS2 = "entry2"; - private final static String ALIAS3 = "entry3"; - private static void test(Provider p, PrivateKeyEntry entry) throws Exception { PrivateKey key = entry.getPrivateKey(); X509Certificate[] chain = (X509Certificate[])entry.getCertificateChain(); @@ -122,11 +127,8 @@ PrivateKey key2 = (PrivateKey)ks.getKey(ALIAS1, null); System.out.println(toString(key2)); - X509Certificate[] chain2 = (X509Certificate[])ks.getCertificateChain(ALIAS1); - // NSS makes token keys always sensitive, skip this check -// if (key.equals(key2) == false) { -// throw new Exception("key mismatch"); -// } + X509Certificate[] chain2 = + (X509Certificate[]) ks.getCertificateChain(ALIAS1); if (Arrays.equals(chain, chain2) == false) { throw new Exception("chain mismatch"); } @@ -154,7 +156,8 @@ PrivateKey key4 = (PrivateKey)ks.getKey(ALIAS2, null); System.out.println(toString(key4)); - X509Certificate[] chain4 = (X509Certificate[])ks.getCertificateChain(ALIAS2); + X509Certificate[] chain4 = (X509Certificate[]) + ks.getCertificateChain(ALIAS2); if (Arrays.equals(chain, chain4) == false) { throw new Exception("chain mismatch"); } @@ -172,7 +175,8 @@ PrivateKey key5 = (PrivateKey)ks.getKey(ALIAS3, null); System.out.println(toString(key5)); - X509Certificate[] chain5 = (X509Certificate[])ks.getCertificateChain(ALIAS3); + X509Certificate[] chain5 = (X509Certificate[]) + ks.getCertificateChain(ALIAS3); if (Arrays.equals(chain, chain5) == false) { throw new Exception("chain mismatch"); } @@ -186,24 +190,22 @@ System.out.println("OK"); } - private final static byte[] DATA = new byte[4096]; - - static { - Random random = new Random(); - random.nextBytes(DATA); - } - - private static void sign(Provider p, PrivateKey privateKey, PublicKey publicKey) throws Exception { + private static void sign(Provider p, PrivateKey privateKey, + PublicKey publicKey) throws Exception { String keyAlg = privateKey.getAlgorithm(); String alg; - if (keyAlg.equals("RSA")) { - alg = "SHA1withRSA"; - } else if (keyAlg.equals("DSA")) { - alg = "SHA1withDSA"; - } else if (keyAlg.equals("EC")) { - alg = "SHA1withECDSA"; - } else { - throw new Exception("Unknown algorithm " + keyAlg); + switch (keyAlg) { + case "RSA": + alg = "SHA1withRSA"; + break; + case "DSA": + alg = "SHA1withDSA"; + break; + case "EC": + alg = "SHA1withECDSA"; + break; + default: + throw new Exception("Unknown algorithm " + keyAlg); } Signature s = Signature.getInstance(alg, p); s.initSign(privateKey); @@ -217,8 +219,6 @@ } } - private final static int MAX_LINE = 85; - private static String toString(Object o) { String s = String.valueOf(o).split("\n")[0]; return (s.length() <= MAX_LINE) ? s : s.substring(0, MAX_LINE); diff -r 7ecf45f5fa46 -r e77968f864eb test/sun/security/pkcs11/Secmod/AddTrustedCert.java --- a/test/sun/security/pkcs11/Secmod/AddTrustedCert.java Thu Sep 10 14:55:20 2015 -0700 +++ b/test/sun/security/pkcs11/Secmod/AddTrustedCert.java Tue Sep 15 07:47:44 2015 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2015, 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 @@ -44,29 +44,47 @@ return; } - InputStream in = new FileInputStream(BASE + SEP + "anchor.cer"); - CertificateFactory factory = CertificateFactory.getInstance("X.509"); - X509Certificate cert = (X509Certificate)factory.generateCertificate(in); - in.close(); -// System.out.println(cert); + X509Certificate cert; + try (InputStream in = new FileInputStream(BASE + SEP + "anchor.cer")) { + CertificateFactory factory = + CertificateFactory.getInstance("X.509"); + cert = (X509Certificate)factory.generateCertificate(in); + } String configName = BASE + SEP + "nss.cfg"; Provider p = getSunPKCS11(configName); System.out.println(p); Security.addProvider(p); - KeyStore ks = KeyStore.getInstance("PKCS11", p); + KeyStore ks = KeyStore.getInstance(PKCS11, p); ks.load(null, password); - Collection aliases = new TreeSet(Collections.list(ks.aliases())); + Collection aliases = new TreeSet<>(Collections.list( + ks.aliases())); System.out.println("entries: " + aliases.size()); System.out.println(aliases); int size1 = aliases.size(); String alias = "anchor"; - ks.setCertificateEntry(alias, cert); + if (ks.containsAlias(alias)) { + throw new Exception("Alias exists: " + alias); + } + ks.setCertificateEntry(alias, cert); + KeyStore.Entry first = ks.getEntry(alias, null); + System.out.println("first entry = " + first); + if (!ks.entryInstanceOf(alias, TrustedCertificateEntry.class)) { + throw new Exception("Unexpected first entry type: " + first); + } - aliases = new TreeSet(Collections.list(ks.aliases())); + ks.setCertificateEntry(alias, cert); + KeyStore.Entry second = ks.getEntry(alias, null); + System.out.println("second entry = " + second); + if (!ks.entryInstanceOf(alias, TrustedCertificateEntry.class)) { + throw new Exception("Unexpected second entry type: " + + second); + } + + aliases = new TreeSet<>(Collections.list(ks.aliases())); System.out.println("entries: " + aliases.size()); System.out.println(aliases); int size2 = aliases.size(); @@ -79,8 +97,12 @@ throw new Exception("KeyStore returned incorrect certificate"); } + ks.deleteEntry(alias); + if (ks.containsAlias(alias)) { + throw new Exception("Alias still exists: " + alias); + } + System.out.println("OK"); - } } diff -r 7ecf45f5fa46 -r e77968f864eb test/sun/security/pkcs11/Secmod/Crypto.java --- a/test/sun/security/pkcs11/Secmod/Crypto.java Thu Sep 10 14:55:20 2015 -0700 +++ b/test/sun/security/pkcs11/Secmod/Crypto.java Tue Sep 15 07:47:44 2015 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2015, 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 @@ -28,11 +28,8 @@ * @author Andreas Sterbenz * @library .. * @run main/othervm Crypto - * @key randomness */ -import java.util.*; - import java.security.*; public class Crypto extends SecmodTest { @@ -51,9 +48,7 @@ System.out.println(kp.getPublic()); System.out.println(kp.getPrivate()); - SecureRandom random = new SecureRandom(); - byte[] data = new byte[2048]; - random.nextBytes(data); + byte[] data = generateData(2048); Signature sig = Signature.getInstance("SHA1withRSA", p); sig.initSign(kp.getPrivate()); diff -r 7ecf45f5fa46 -r e77968f864eb test/sun/security/pkcs11/Secmod/GetPrivateKey.java --- a/test/sun/security/pkcs11/Secmod/GetPrivateKey.java Thu Sep 10 14:55:20 2015 -0700 +++ b/test/sun/security/pkcs11/Secmod/GetPrivateKey.java Tue Sep 15 07:47:44 2015 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2015, 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 @@ -24,11 +24,11 @@ /** * @test * @bug 6273877 6322208 6275523 - * @summary make sure we can access the NSS softtoken KeyStore and use a private key + * @summary make sure we can access the NSS softtoken KeyStore + * and use a private key * @author Andreas Sterbenz * @library .. * @run main/othervm GetPrivateKey - * @key randomness */ import java.util.*; @@ -49,18 +49,17 @@ System.out.println(p); Security.addProvider(p); - KeyStore ks = KeyStore.getInstance("PKCS11", p); + KeyStore ks = KeyStore.getInstance(PKCS11, p); ks.load(null, password); - Collection aliases = new TreeSet(Collections.list(ks.aliases())); + Collection aliases = new TreeSet<>( + Collections.list(ks.aliases())); System.out.println("entries: " + aliases.size()); System.out.println(aliases); PrivateKey privateKey = (PrivateKey)ks.getKey(keyAlias, password); System.out.println(privateKey); - byte[] data = new byte[1024]; - Random random = new Random(); - random.nextBytes(data); + byte[] data = generateData(1024); System.out.println("Signing..."); Signature signature = Signature.getInstance("MD5withRSA"); @@ -68,7 +67,8 @@ signature.update(data); byte[] sig = signature.sign(); - X509Certificate[] chain = (X509Certificate[])ks.getCertificateChain(keyAlias); + X509Certificate[] chain = + (X509Certificate[]) ks.getCertificateChain(keyAlias); signature.initVerify(chain[0].getPublicKey()); signature.update(data); boolean ok = signature.verify(sig); diff -r 7ecf45f5fa46 -r e77968f864eb test/sun/security/pkcs11/Secmod/LoadKeystore.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test/sun/security/pkcs11/Secmod/LoadKeystore.java Tue Sep 15 07:47:44 2015 -0700 @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2015, 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. + */ + +import java.io.IOException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.Provider; +import java.security.Security; +import java.security.UnrecoverableKeyException; +import java.util.Collections; + +/* + * @test + * @bug 8048622 8134232 + * @summary Checks that PKCS#11 keystore can't be loaded with wrong password + * @library ../ + * @run main/othervm LoadKeystore + */ +public class LoadKeystore extends SecmodTest { + + public static void main(String[] args) throws Exception { + if (!initSecmod()) { + return; + } + + String configName = BASE + SEP + "nss.cfg"; + Provider p = getSunPKCS11(configName); + + System.out.println("Add provider " + p); + System.out.println(); + Security.addProvider(p); + + try { + System.out.println("Load keystore with wrong type"); + KeyStore.getInstance("unknown", p); + throw new RuntimeException("Expected exception not thrown"); + } catch(KeyStoreException e) { + System.out.println("Expected exception: " + e); + } + + KeyStore ks = KeyStore.getInstance("PKCS11", p); + if (!"PKCS11".equals(ks.getType())) { + throw new RuntimeException("Unexpected keystore type: " + + ks.getType()); + } + if (!p.equals(ks.getProvider())) { + throw new RuntimeException("Unexpected keystore provider: " + + ks.getProvider()); + } + + try { + System.out.println("Load keystore with wrong password"); + ks.load(null, "wrong".toCharArray()); + throw new RuntimeException("Expected exception not thrown"); + } catch(IOException e) { + System.out.println("Expected exception: " + e); + Throwable cause = e.getCause(); + if (!(cause instanceof UnrecoverableKeyException)) { + e.printStackTrace(System.out); + throw new RuntimeException("Unexpected cause: " + cause); + } + System.out.println("Expected cause: " + cause); + } + + System.out.println("Load keystore with correct password"); + ks.load(null, password); + for (String alias : Collections.list(ks.aliases())) { + System.out.println("Alias: " + alias); + } + + System.out.println("Test passed"); + } + +} diff -r 7ecf45f5fa46 -r e77968f864eb test/sun/security/provider/KeyStore/DKSTest.java --- a/test/sun/security/provider/KeyStore/DKSTest.java Thu Sep 10 14:55:20 2015 -0700 +++ b/test/sun/security/provider/KeyStore/DKSTest.java Tue Sep 15 07:47:44 2015 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2015, 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 @@ -60,8 +60,38 @@ new KeyStore.PasswordProtection("passphrase".toCharArray())); }}; + private static final Map + WRONG_PASSWORDS = new HashMap() {{ + put("policy_keystore", + new KeyStore.PasswordProtection( + "wrong".toCharArray())); + put("pw_keystore", + new KeyStore.PasswordProtection("wrong".toCharArray())); + put("eckeystore1", + new KeyStore.PasswordProtection("wrong".toCharArray())); + put("eckeystore2", + new KeyStore.PasswordProtection("wrong".toCharArray())); + }}; + public static void main(String[] args) throws Exception { /* + * domain keystore: keystores with wrong passwords + */ + try { + URI config = new URI(CONFIG + "#keystores"); + KeyStore ks = KeyStore.getInstance("DKS"); + ks.load(new DomainLoadStoreParameter(config, WRONG_PASSWORDS)); + throw new RuntimeException("Expected exception not thrown"); + } catch (IOException e) { + System.out.println("Expected exception: " + e); + if (!causedBy(e, UnrecoverableKeyException.class)) { + e.printStackTrace(System.out); + throw new RuntimeException("Unexpected cause"); + } + System.out.println("Expected cause: " + e); + } + + /* * domain keystore: system */ URI config = new URI(CONFIG + "#system"); @@ -182,4 +212,15 @@ return factory.generateCertificate(certStream); } } + + // checks if an exception was caused by specified exception class + private static boolean causedBy(Exception e, Class klass) { + Throwable cause = e; + while ((cause = cause.getCause()) != null) { + if (cause.getClass().equals(klass)) { + return true; + } + } + return false; + } }