changeset 12882:bd24ee3a9a04 jdk8u172-b03

Merge
author asaha
date Tue, 16 Jan 2018 22:58:44 -0800
parents 51b6cc7fbd98 (current diff) d201d8b87f48 (diff)
children 19c65add5760 d0e3f3cf28b6
files .hgtags src/share/classes/javax/swing/JList.java src/share/classes/sun/misc/JavaObjectInputStreamAccess.java src/share/classes/sun/misc/ObjectStreamClassValidator.java src/share/classes/sun/print/RasterPrinterJob.java src/share/classes/sun/security/ssl/SupportedEllipticCurvesExtension.java src/share/classes/sun/security/ssl/SupportedEllipticPointFormatsExtension.java src/share/classes/sun/security/tools/keytool/Main.java src/windows/native/sun/windows/awt_Component.cpp
diffstat 152 files changed, 6075 insertions(+), 1607 deletions(-) [+]
line wrap: on
line diff
--- a/.hgtags	Mon Jan 08 22:36:23 2018 -0800
+++ b/.hgtags	Tue Jan 16 22:58:44 2018 -0800
@@ -664,6 +664,8 @@
 60767ec3909b3d0cb26dd7b3f952c62053719dda jdk8u112-b15
 5dd7e4bae5c2f1ee4f80c5570e7e3e2f715f7a32 jdk8u112-b16
 41fac11792c1ee6945f56721ee558a7424395a81 jdk8u112-b31
+548a51660ee94aeb77b2432594aeb87f87c21697 jdk8u112-b32
+a334b0815d34948188537a177a32cee27007ea2c jdk8u112-b33
 ab5ff8f1e52c5e3ca02e988f4d978af63ceca5b8 jdk8u121-b00
 5f0839ac7e0d25dd1ae705df496b12ca76c26d59 jdk8u121-b01
 f91e3aa155b3c6774afb456db15fb358313d5771 jdk8u121-b02
@@ -678,6 +680,12 @@
 ec72a941be0a50ab77f5375cf710bc06e4f118d3 jdk8u121-b11
 9561afc12df843ef21ecd9d7b3633371e7a2bfc4 jdk8u121-b12
 2974746e56192cdd14fc2dd43179bcf28e4faf4a jdk8u121-b13
+4f69f3363a2ecee8d3df2b046266a76c2a805139 jdk8u121-b31
+ec26e3331158912f86268ef473e64514c70cbd52 jdk8u121-b32
+cb2c7c89dd09edcda4cb7bd0db623c813d3e5dbc jdk8u121-b33
+90f36d39acdc5be0665722538749c59583e3b83d jdk8u121-b34
+cec5310dcc2b876dd53a057035cb63dd22f63257 jdk8u121-b35
+a5c94735ad3fb33f353abc23e25915db2ff7a36e jdk8u121-b36
 032874d46bf95478cb86690b3c91d335c0764b0b jdk8u131-b00
 bea5b22daf5ddd941f3bcbf7a4e5fc5244ceb788 jdk8u131-b01
 a01d217a232906e82f80e5bc3db4d60c4c74716e jdk8u131-b02
@@ -690,6 +698,10 @@
 40d00399869d8a28cfecf360234f340e9e0ad3b1 jdk8u131-b09
 c0091a673d766ce2e76a945bab6de325fe78dd88 jdk8u131-b10
 3ab471c4760a808e39406303ff33a25a542b9c75 jdk8u131-b11
+d50ccb38def5968145fd3f6e0579416bb027e85c jdk8u131-b31
+e54624a8ebe3639d3b2360adb9ae0fa32f1bef57 jdk8u131-b32
+15006e8dc79bd0005d264bff0b1677a109cf5a02 jdk8u131-b33
+e6e35f065443533c81db69022a272927b0b20f69 jdk8u131-b34
 a160009bbe1417d85f1c0eec890fdb17391b3637 jdk8u141-b00
 e95a13de2d36050302a1af422967f5260fc8eabd jdk8u141-b01
 936085d9aff0554a3bdab2fcbbec1d1864e656a2 jdk8u141-b02
@@ -712,6 +724,14 @@
 2ea94405100763c772ab3989200115d7a23c7532 jdk8u141-b15
 b64b1dfdbe7cfe3859f1023c0f1fb0216bce4ae7 jdk8u144-b00
 d2744852f3e64f7b0ba54f3a64ed5e2107e6ee68 jdk8u144-b01
+55899d2b99b0725d74eebc510a116423329ad6f0 jdk8u141-b31
+a3c4020f84aeb0dba467534239951f8818bdfb84 jdk8u141-b32
+b64b1dfdbe7cfe3859f1023c0f1fb0216bce4ae7 jdk8u144-b00
+d2744852f3e64f7b0ba54f3a64ed5e2107e6ee68 jdk8u144-b01
+a05113a4c91c59f44b9894e12aeda07a7534ff7e jdk8u144-b31
+c4f7f2878c4bc54dcc12eddbbcd90d4c7a5dddfe jdk8u144-b32
+785d45a4c0b715ff0131abda873e3c2f85874ac3 jdk8u144-b33
+71dee2264dddd5a2c90d8c6f3a3f4ffd8da02551 jdk8u144-b34
 072e084bceeedeb75467e40ca77786ac9ef5227a jdk8u151-b00
 5b0fa6e004312a5910a6a70e4fbc0f00a678e650 jdk8u151-b01
 bd40efd56b4544ff9048d2f7be4cf108b281a6f3 jdk8u151-b02
@@ -752,10 +772,85 @@
 50047f057dc14fa5e08e2b449304a21889e4079a jdk8u152-b14
 bfd67d7c7d41b320225d5502cec55c6b38cdaa6d jdk8u152-b15
 1cb70967c4d78a45a60d0d6eb64cb7fbe89ad005 jdk8u152-b16
+072e084bceeedeb75467e40ca77786ac9ef5227a jdk8u151-b00
+5b0fa6e004312a5910a6a70e4fbc0f00a678e650 jdk8u151-b01
+bd40efd56b4544ff9048d2f7be4cf108b281a6f3 jdk8u151-b02
+58243fea3fe2669e93350bb4b77e188623b85503 jdk8u151-b03
+27273bbb711a402efe5fcd332003ba419102f662 jdk8u151-b04
+0efdf2c7a21464e5f3d89474ffdfe81db61031fd jdk8u151-b05
+c6c870e267de694bc85dc4af23a648824063f95b jdk8u151-b06
+1442bc728814af451e2dd1a6719a64485d27e3a0 jdk8u122-b00
+f6030acfa5aec0e64d45adfac69b9e7e5c12bc74 jdk8u122-b01
+6b072c3a6db7ab06804c91aab77431799dfb5d47 jdk8u122-b02
+141beb4d854d213c1aefcc4406f09aa6b0809e43 jdk8u122-b03
+141beb4d854d213c1aefcc4406f09aa6b0809e43 jdk8u122-b03
+0000000000000000000000000000000000000000 jdk8u122-b03
+0000000000000000000000000000000000000000 jdk8u122-b03
+d8c1eb38a23286991238eed87ab04c331700839b jdk8u122-b03
+774f11d707e0ff685c131cd625d96e1f58527990 jdk8u122-b04
+000711011f8ab7ab5ea88e02086c48181b42ab8f jdk8u132-b00
+f7be58eb30bc2cdea8a8e0fb254f52f176f5b57d jdk8u152-b00
+072df97b6e2af59f5e2433ae6b2dbecb16b03cd8 jdk8u152-b01
+dbf817e782805bffcb9a0d84f452349926329d62 jdk8u152-b02
+824988d089dde02e15f04c3b994115f78b9408c9 jdk8u152-b03
+4c95cacb8ec77cbda2ae1d4e070b39ec6b527769 jdk8u152-b04
+9c692f8574178a5505efe39cdff1ea92d4f95cbd jdk8u152-b05
+636043375508d667052c84691c55d4c633376dbe jdk8u152-b06
+83998ef9e0b96e1f5f9d4667575a81e8aa06b981 jdk8u152-b07
+e62e091df75fd92bf9d8c573f6224132c99b33ea jdk8u152-b08
+eb71140d49732a226340c0e0a2224c0215fc161a jdk8u152-b09
+1442bc728814af451e2dd1a6719a64485d27e3a0 jdk8u122-b00
+f6030acfa5aec0e64d45adfac69b9e7e5c12bc74 jdk8u122-b01
+6b072c3a6db7ab06804c91aab77431799dfb5d47 jdk8u122-b02
+141beb4d854d213c1aefcc4406f09aa6b0809e43 jdk8u122-b03
+141beb4d854d213c1aefcc4406f09aa6b0809e43 jdk8u122-b03
+0000000000000000000000000000000000000000 jdk8u122-b03
+0000000000000000000000000000000000000000 jdk8u122-b03
+d8c1eb38a23286991238eed87ab04c331700839b jdk8u122-b03
+774f11d707e0ff685c131cd625d96e1f58527990 jdk8u122-b04
+000711011f8ab7ab5ea88e02086c48181b42ab8f jdk8u132-b00
+f7be58eb30bc2cdea8a8e0fb254f52f176f5b57d jdk8u152-b00
+072df97b6e2af59f5e2433ae6b2dbecb16b03cd8 jdk8u152-b01
+dbf817e782805bffcb9a0d84f452349926329d62 jdk8u152-b02
+824988d089dde02e15f04c3b994115f78b9408c9 jdk8u152-b03
+4c95cacb8ec77cbda2ae1d4e070b39ec6b527769 jdk8u152-b04
+9c692f8574178a5505efe39cdff1ea92d4f95cbd jdk8u152-b05
+a160009bbe1417d85f1c0eec890fdb17391b3637 jdk8u141-b00
+072e084bceeedeb75467e40ca77786ac9ef5227a jdk8u151-b00
+e9c7ecc5a9fcdcb31d4796b72493960c271dcb31 jdk8u161-b00
+3b1bfef6f82b72cc7e8d73a60d1faaf7818be6f3 jdk8u161-b01
+fef2bdb968d7caa0d4bd1714bd4571ca21edb25d jdk8u161-b02
+3742cb9c55fd997075a52581497829bd6f6b978a jdk8u161-b03
+3299bb548705c586c17fc31c815bb222e6a63370 jdk8u161-b04
+1c28a0748a119120a4c3a52b9a73d18ed2d1926a jdk8u161-b05
+7399fd6431c74464d3392a7d76715580039c50ea jdk8u161-b06
+cb84156d54b28d4e59159a513db7c4e9dc693f9e jdk8u161-b07
+cb84156d54b28d4e59159a513db7c4e9dc693f9e jdk8u161-b07
+0000000000000000000000000000000000000000 jdk8u161-b07
+0000000000000000000000000000000000000000 jdk8u161-b07
+22f4dc5bcb9955e02bb4e3b7fb847fd08339dd2d jdk8u161-b07
+e7c79f48e83772546a1d35d98101853e2ca17947 jdk8u161-b08
+2c4e596e0cc3281fe976d9a730677c0a15113153 jdk8u161-b09
+3eaad567db074e4d3df7d4088a4a029ef5ad1179 jdk8u161-b10
+8d358ca3cfb813af87aa4bed5a1e7fbb678ea6be jdk8u161-b11
+76f2c555cccab8df114dd6ebb8ed7634c7ce1896 jdk8u161-b12
 e03f9868f7df1e3db537f3b61704658e8a9dafb5 jdk8u162-b00
 538bdf24383954cd2356e39e8081c2cb3ac27281 jdk8u162-b01
 18e0bc77adafd0e5e459e381b6993bb0625b05be jdk8u162-b02
 e1e7eee76e15fd386fd22b556c916635b4e113ab jdk8u162-b03
+4c4efa8fa39ae0fe73638eeeb84546da4d010aef jdk8u162-b04
+a651df33d9a07d9fc4411de4854e9528d8708a6f jdk8u162-b05
+582c82cfebe262f2934e3577dc8809ec8acbbd87 jdk8u162-b06
+672bbe9bcdd79a72308e21dd67f560d4fe806f49 jdk8u162-b07
+672bbe9bcdd79a72308e21dd67f560d4fe806f49 jdk8u162-b07
+0000000000000000000000000000000000000000 jdk8u162-b07
+0000000000000000000000000000000000000000 jdk8u162-b07
+fce5b32117cc0b06acc2bcaa364ac62539d42707 jdk8u162-b07
+c9254e01820639526f803dbe05080fce0d33db98 jdk8u162-b08
+1aa2e6ec537c3dd0fd4f9780f16da3e38fb18cee jdk8u162-b09
+1d2ee5e60df1c3bc889c92154d839bfe73077f66 jdk8u162-b10
+95df717479b19f5ea244afc67434827f2f851287 jdk8u162-b11
+ddae5cb11d6c04130b8002b852bc7f80e0c8bcd2 jdk8u162-b12
 64df143be721d3ef031d765d86277c1e114d627a jdk8u172-b00
 25f7b0cd25cf13106783050fc8e6f4a78487a7bd jdk8u172-b01
 db8272cb8c99eea536a66c4c368c4bf2bf013a81 jdk8u172-b02
--- a/THIRD_PARTY_README	Mon Jan 08 22:36:23 2018 -0800
+++ b/THIRD_PARTY_README	Tue Jan 16 22:58:44 2018 -0800
@@ -7,7 +7,7 @@
 
 --- begin of LICENSE ---
 
-Copyright (c) 2000-2011 France Télécom
+Copyright (c) 2000-2011 France T??l??com
 All rights reserved.
 
 Redistribution and use in source and binary forms, with or without
@@ -849,7 +849,7 @@
 --- begin of LICENSE ---
 
 Copyright notice
-Copyright © 2011 Ecma International
+Copyright ?? 2011 Ecma International
 Ecma International
 Rue du Rhone 114
 CH-1204 Geneva
@@ -916,7 +916,7 @@
 
 --- begin of LICENSE ---
 
-Copyright © 2001,2003 Keith Packard
+Copyright ?? 2001,2003 Keith Packard
 
 Permission to use, copy, modify, distribute, and sell this software and its
 documentation for any purpose is hereby granted without fee, provided that the
@@ -2212,16 +2212,16 @@
 Unicode Terms of Use
 
 For the general privacy policy governing access to this site, see the Unicode
-Privacy Policy. For trademark usage, see the Unicode® Consortium Name and
+Privacy Policy. For trademark usage, see the Unicode?? Consortium Name and
 Trademark Usage Policy.
 
 A. Unicode Copyright.
-   1. Copyright © 1991-2013 Unicode, Inc. All rights reserved.
+   1. Copyright ?? 1991-2013 Unicode, Inc. All rights reserved.
 
    2. Certain documents and files on this website contain a legend indicating
       that "Modification is permitted." Any person is hereby authorized,
       without fee, to modify such documents and files to create derivative
-      works conforming to the Unicode® Standard, subject to Terms and
+      works conforming to the Unicode?? Standard, subject to Terms and
       Conditions herein.
 
     3. Any person is hereby authorized, without fee, to view, use, reproduce,
@@ -2287,14 +2287,14 @@
 
 E.Trademarks & Logos.
    1. The Unicode Word Mark and the Unicode Logo are trademarks of Unicode,
-      Inc.  “The Unicode Consortium” and “Unicode, Inc.” are trade names of
+      Inc.  ???The Unicode Consortium??? and ???Unicode, Inc.??? are trade names of
       Unicode, Inc.  Use of the information and materials found on this
-      website indicates your acknowledgement of Unicode, Inc.’s exclusive
+      website indicates your acknowledgement of Unicode, Inc.???s exclusive
       worldwide rights in the Unicode Word Mark, the Unicode Logo, and the
       Unicode trade names.
 
-   2. The Unicode Consortium Name and Trademark Usage Policy (“Trademark
-      Policy”) are incorporated herein by reference and you agree to abide by
+   2. The Unicode Consortium Name and Trademark Usage Policy (???Trademark
+      Policy???) are incorporated herein by reference and you agree to abide by
       the provisions of the Trademark Policy, which may be changed from time
       to time in the sole discretion of Unicode, Inc.
 
@@ -2317,12 +2317,12 @@
 
    2. Modification by Unicode.  Unicode shall have the right to modify this
       Agreement at any time by posting it to this site. The user may not
-      assign any part of this Agreement without Unicode’s prior written
+      assign any part of this Agreement without Unicode???s prior written
       consent.
 
    3. Taxes. The user agrees to pay any taxes arising from access to this
       website or use of the information herein, except for those based on
-      Unicode’s net income.
+      Unicode???s net income.
 
    4. Severability.  If any provision of this Agreement is declared invalid or
       unenforceable, the remaining provisions of this Agreement shall remain
@@ -2351,7 +2351,7 @@
 
 COPYRIGHT AND PERMISSION NOTICE
 
-Copyright © 1991-2012 Unicode, Inc. All rights reserved. Distributed under the
+Copyright ?? 1991-2012 Unicode, Inc. All rights reserved. Distributed under the
 Terms of Use in http://www.unicode.org/copyright.html.
 
 Permission is hereby granted, free of charge, to any person obtaining a copy
--- a/make/Images.gmk	Mon Jan 08 22:36:23 2018 -0800
+++ b/make/Images.gmk	Tue Jan 16 22:58:44 2018 -0800
@@ -550,6 +550,9 @@
 	$(MKDIR) -p $(JDK_IMAGE_DIR)/db
 	cd $(JDK_IMAGE_DIR)/db && $(UNZIP) -q -o $< -x */index.html */KEYS */test/* *javadoc/* */docs/* */demo/* 2> /dev/null
 	cd $(JDK_IMAGE_DIR)/db && $(MV) db-derby-*-bin/* . && $(RM) -r db-derby-*-bin
+ifneq ($(OPENJDK_TARGET_OS), windows)
+	$(RM) $(JDK_IMAGE_DIR)/db/bin/*.bat
+endif
 	$(MKDIR) -p $(@D)
 	$(TOUCH) $@
 
--- a/make/profile-rtjar-includes.txt	Mon Jan 08 22:36:23 2018 -0800
+++ b/make/profile-rtjar-includes.txt	Tue Jan 16 22:58:44 2018 -0800
@@ -90,6 +90,7 @@
     javax/sql \
     javax/transaction \
     javax/xml \
+    jdk/xml/internal \
     org/w3c \
     org/xml/sax \
     sun/net/httpserver \
--- a/src/macosx/native/apple/security/KeystoreImpl.m	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/macosx/native/apple/security/KeystoreImpl.m	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2017, 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
@@ -432,6 +432,11 @@
                 goto errOut;
             }
             passwordStrRef = CFStringCreateWithCharacters(kCFAllocatorDefault, passwordChars, passwordLen);
+
+            // clear the password and release
+            memset(passwordChars, 0, passwordLen);
+            (*env)->ReleaseCharArrayElements(env, passwordObj, passwordChars,
+                JNI_ABORT);
         }
     }
 
@@ -518,8 +523,19 @@
 
     if (passwordObj) {
         passwordLen = (*env)->GetArrayLength(env, passwordObj);
-        passwordChars = (*env)->GetCharArrayElements(env, passwordObj, NULL);
-        passwordStrRef = CFStringCreateWithCharacters(kCFAllocatorDefault, passwordChars, passwordLen);
+
+        if (passwordLen > 0) {
+            passwordChars = (*env)->GetCharArrayElements(env, passwordObj, NULL);
+            if (passwordChars == NULL) {
+                goto errOut;
+            }
+            passwordStrRef = CFStringCreateWithCharacters(kCFAllocatorDefault, passwordChars, passwordLen);
+
+            // clear the password and release
+            memset(passwordChars, 0, passwordLen);
+            (*env)->ReleaseCharArrayElements(env, passwordObj, passwordChars,
+                JNI_ABORT);
+        }
     }
 
     paramBlock.version = SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION;
--- a/src/share/classes/com/sun/accessibility/internal/resources/accessibility_ko.properties	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/com/sun/accessibility/internal/resources/accessibility_ko.properties	Tue Jan 16 22:58:44 2018 -0800
@@ -14,7 +14,7 @@
 # accessible roles
 #
 alert=\uACBD\uBCF4
-awtcomponent=AWT \uAD6C\uC131 \uC694\uC18C
+awtcomponent=AWT \uAD6C\uC131\uC694\uC18C
 checkbox=\uCCB4\uD06C\uBC15\uC2A4
 colorchooser=\uC0C9\uC0C1 \uC120\uD0DD\uAE30
 columnheader=\uC5F4 \uBA38\uB9AC\uAE00
@@ -52,7 +52,7 @@
 separator=\uAD6C\uBD84 \uAE30\uD638
 slider=\uC2AC\uB77C\uC774\uB354
 splitpane=\uBD84\uD560 \uCC3D
-swingcomponent=\uD68C\uC804 \uAD6C\uC131 \uC694\uC18C
+swingcomponent=\uD68C\uC804 \uAD6C\uC131\uC694\uC18C
 table=\uD14C\uC774\uBE14
 text=\uD14D\uC2A4\uD2B8
 tree=\uD2B8\uB9AC
--- a/src/share/classes/com/sun/crypto/provider/DESKey.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/com/sun/crypto/provider/DESKey.java	Tue Jan 16 22:58:44 2018 -0800
@@ -76,7 +76,7 @@
         DESKeyGenerator.setParityBit(this.key, 0);
     }
 
-    public byte[] getEncoded() {
+    public synchronized byte[] getEncoded() {
         // Return a copy of the key, rather than a reference,
         // so that the key data cannot be modified from outside
         return this.key.clone();
@@ -151,9 +151,11 @@
      */
     protected void finalize() throws Throwable {
         try {
-            if (this.key != null) {
-                java.util.Arrays.fill(this.key, (byte)0x00);
-                this.key = null;
+            synchronized (this) {
+                if (this.key != null) {
+                    java.util.Arrays.fill(this.key, (byte)0x00);
+                    this.key = null;
+                }
             }
         } finally {
             super.finalize();
--- a/src/share/classes/com/sun/crypto/provider/DESedeKey.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/com/sun/crypto/provider/DESedeKey.java	Tue Jan 16 22:58:44 2018 -0800
@@ -78,7 +78,7 @@
         DESKeyGenerator.setParityBit(this.key, 16);
     }
 
-    public byte[] getEncoded() {
+    public synchronized byte[] getEncoded() {
         return this.key.clone();
     }
 
@@ -152,9 +152,11 @@
      */
     protected void finalize() throws Throwable {
         try {
-            if (this.key != null) {
-                java.util.Arrays.fill(this.key, (byte)0x00);
-                this.key = null;
+            synchronized (this) {
+                if (this.key != null) {
+                    java.util.Arrays.fill(this.key, (byte)0x00);
+                    this.key = null;
+                }
             }
         } finally {
             super.finalize();
--- a/src/share/classes/com/sun/crypto/provider/DHKeyAgreement.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/com/sun/crypto/provider/DHKeyAgreement.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, 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,13 @@
 import java.util.*;
 import java.lang.*;
 import java.math.BigInteger;
+import java.security.AccessController;
 import java.security.InvalidAlgorithmParameterException;
 import java.security.InvalidKeyException;
 import java.security.Key;
 import java.security.NoSuchAlgorithmException;
 import java.security.SecureRandom;
+import java.security.PrivilegedAction;
 import java.security.ProviderException;
 import java.security.spec.AlgorithmParameterSpec;
 import java.security.spec.InvalidKeySpecException;
@@ -60,6 +62,17 @@
     private BigInteger x = BigInteger.ZERO; // the private value
     private BigInteger y = BigInteger.ZERO;
 
+    private static class AllowKDF {
+
+        private static final boolean VALUE = getValue();
+
+        private static boolean getValue() {
+            return AccessController.doPrivileged(
+                (PrivilegedAction<Boolean>)
+                () -> Boolean.getBoolean("jdk.crypto.KeyAgreement.legacyKDF"));
+        }
+    }
+
     /**
      * Empty constructor
      */
@@ -367,6 +380,14 @@
         if (algorithm == null) {
             throw new NoSuchAlgorithmException("null algorithm");
         }
+
+        if (!algorithm.equalsIgnoreCase("TlsPremasterSecret") &&
+            !AllowKDF.VALUE) {
+
+            throw new NoSuchAlgorithmException("Unsupported secret key "
+                                               + "algorithm: " + algorithm);
+        }
+
         byte[] secret = engineGenerateSecret();
         if (algorithm.equalsIgnoreCase("DES")) {
             // DES
--- a/src/share/classes/com/sun/crypto/provider/DHKeyPairGenerator.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/com/sun/crypto/provider/DHKeyPairGenerator.java	Tue Jan 16 22:58:44 2018 -0800
@@ -74,10 +74,10 @@
     private static void checkKeySize(int keysize)
             throws InvalidParameterException {
 
-        if ((keysize < 512) || (keysize > 2048) || ((keysize & 0x3F) != 0)) {
+        if ((keysize < 512) || (keysize > 8192) || ((keysize & 0x3F) != 0)) {
             throw new InvalidParameterException(
                     "DH key size must be multiple of 64, and can only range " +
-                    "from 512 to 2048 (inclusive). " +
+                    "from 512 to 8192 (inclusive). " +
                     "The specific key size " + keysize + " is not supported");
         }
     }
@@ -91,12 +91,23 @@
      * @param random the source of randomness
      */
     public void initialize(int keysize, SecureRandom random) {
+
         checkKeySize(keysize);
 
+        // Use the built-in parameters (ranging from 512 to 8192)
+        // when available.
+        this.params = ParameterCache.getCachedDHParameterSpec(keysize);
+
+        // Due to performance issue, only support DH parameters generation
+        // up to 1024 bits.
+        if ((this.params == null) && (keysize > 1024)) {
+            throw new InvalidParameterException(
+                "Unsupported " + keysize + "-bit DH parameter generation");
+        }
+
         this.pSize = keysize;
         this.lSize = 0;
         this.random = random;
-        this.params = null;
     }
 
     /**
--- a/src/share/classes/com/sun/crypto/provider/DHParameterGenerator.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/com/sun/crypto/provider/DHParameterGenerator.java	Tue Jan 16 22:58:44 2018 -0800
@@ -25,6 +25,7 @@
 
 package com.sun.crypto.provider;
 
+import java.math.BigInteger;
 import java.security.*;
 import java.security.spec.*;
 import javax.crypto.spec.DHParameterSpec;
@@ -47,8 +48,7 @@
  * @see java.security.spec.AlgorithmParameterSpec
  * @see DHParameters
  */
-public final class DHParameterGenerator
-extends AlgorithmParameterGeneratorSpi {
+public final class DHParameterGenerator extends AlgorithmParameterGeneratorSpi {
 
     // The size in bits of the prime modulus
     private int primeSize = DEF_DH_KEY_SIZE;
@@ -61,11 +61,13 @@
 
     private static void checkKeySize(int keysize)
             throws InvalidParameterException {
-            if ((keysize != 2048) &&
-            ((keysize < 512) || (keysize > 1024) || (keysize % 64 != 0))) {
+        boolean supported = ((keysize == 2048) || (keysize == 3072) ||
+            ((keysize >= 512) && (keysize <= 1024) && ((keysize & 0x3F) == 0)));
+
+        if (!supported) {
             throw new InvalidParameterException(
                     "DH key size must be multiple of 64 and range " +
-                    "from 512 to 1024 (inclusive), or 2048. " +
+                    "from 512 to 1024 (inclusive), or 2048, 3072. " +
                     "The specific key size " + keysize + " is not supported");
         }
     }
@@ -78,8 +80,8 @@
      * @param keysize the keysize (size of prime modulus) in bits
      * @param random the source of randomness
      */
+    @Override
     protected void engineInit(int keysize, SecureRandom random) {
-        // Re-uses DSA parameters and thus have the same range
         checkKeySize(keysize);
         this.primeSize = keysize;
         this.random = random;
@@ -96,36 +98,31 @@
      * @exception InvalidAlgorithmParameterException if the given parameter
      * generation values are inappropriate for this parameter generator
      */
+    @Override
     protected void engineInit(AlgorithmParameterSpec genParamSpec,
-                              SecureRandom random)
-        throws InvalidAlgorithmParameterException {
+          SecureRandom random) throws InvalidAlgorithmParameterException {
+
         if (!(genParamSpec instanceof DHGenParameterSpec)) {
             throw new InvalidAlgorithmParameterException
                 ("Inappropriate parameter type");
         }
 
         DHGenParameterSpec dhParamSpec = (DHGenParameterSpec)genParamSpec;
-
         primeSize = dhParamSpec.getPrimeSize();
-
-        // Re-uses DSA parameters and thus have the same range
+        exponentSize = dhParamSpec.getExponentSize();
+        if ((exponentSize <= 0) || (exponentSize >= primeSize)) {
+            throw new InvalidAlgorithmParameterException(
+                    "Exponent size (" + exponentSize +
+                    ") must be positive and less than modulus size (" +
+                    primeSize + ")");
+        }
         try {
             checkKeySize(primeSize);
         } catch (InvalidParameterException ipe) {
             throw new InvalidAlgorithmParameterException(ipe.getMessage());
         }
 
-        exponentSize = dhParamSpec.getExponentSize();
-        if (exponentSize <= 0) {
-            throw new InvalidAlgorithmParameterException
-                ("Exponent size must be greater than zero");
-        }
-
-        // Require exponentSize < primeSize
-        if (exponentSize >= primeSize) {
-            throw new InvalidAlgorithmParameterException
-                ("Exponent size must be less than modulus size");
-        }
+        this.random = random;
     }
 
     /**
@@ -133,24 +130,25 @@
      *
      * @return the new AlgorithmParameters object
      */
+    @Override
     protected AlgorithmParameters engineGenerateParameters() {
-        AlgorithmParameters algParams = null;
 
         if (this.exponentSize == 0) {
             this.exponentSize = this.primeSize - 1;
         }
+        if (random == null) {
+            random = SunJCE.getRandom();
+        }
 
-        if (this.random == null)
-            this.random = SunJCE.getRandom();
-
+        BigInteger paramP = null;
+        BigInteger paramG = null;
         try {
-            AlgorithmParameterGenerator paramGen;
-            DSAParameterSpec dsaParamSpec;
-
-            paramGen = AlgorithmParameterGenerator.getInstance("DSA");
-            paramGen.init(this.primeSize, random);
-            algParams = paramGen.generateParameters();
-            dsaParamSpec = algParams.getParameterSpec(DSAParameterSpec.class);
+            AlgorithmParameterGenerator dsaParamGen =
+                    AlgorithmParameterGenerator.getInstance("DSA");
+            dsaParamGen.init(primeSize, random);
+            AlgorithmParameters dsaParams = dsaParamGen.generateParameters();
+            DSAParameterSpec dsaParamSpec =
+                    dsaParams.getParameterSpec(DSAParameterSpec.class);
 
             DHParameterSpec dhParamSpec;
             if (this.exponentSize > 0) {
@@ -161,16 +159,13 @@
                 dhParamSpec = new DHParameterSpec(dsaParamSpec.getP(),
                                                   dsaParamSpec.getG());
             }
-            algParams = AlgorithmParameters.getInstance("DH",
-                    SunJCE.getInstance());
+            AlgorithmParameters algParams =
+                    AlgorithmParameters.getInstance("DH", SunJCE.getInstance());
             algParams.init(dhParamSpec);
-        } catch (InvalidParameterSpecException e) {
-            // this should never happen
-            throw new RuntimeException(e.getMessage());
-        } catch (NoSuchAlgorithmException e) {
-            // this should never happen, because we provide it
-            throw new RuntimeException(e.getMessage());
+
+            return algParams;
+        } catch (Exception ex) {
+            throw new ProviderException("Unexpected exception", ex);
         }
-        return algParams;
     }
 }
--- a/src/share/classes/com/sun/crypto/provider/PBEKey.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/com/sun/crypto/provider/PBEKey.java	Tue Jan 16 22:58:44 2018 -0800
@@ -72,7 +72,7 @@
         type = keytype;
     }
 
-    public byte[] getEncoded() {
+    public synchronized byte[] getEncoded() {
         return this.key.clone();
     }
 
@@ -147,9 +147,11 @@
      */
     protected void finalize() throws Throwable {
         try {
-            if (this.key != null) {
-                java.util.Arrays.fill(this.key, (byte)0x00);
-                this.key = null;
+            synchronized (this) {
+                if (this.key != null) {
+                    java.util.Arrays.fill(this.key, (byte)0x00);
+                    this.key = null;
+                }
             }
         } finally {
             super.finalize();
--- a/src/share/classes/com/sun/crypto/provider/PBKDF2KeyImpl.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/com/sun/crypto/provider/PBKDF2KeyImpl.java	Tue Jan 16 22:58:44 2018 -0800
@@ -190,7 +190,7 @@
         return key;
     }
 
-    public byte[] getEncoded() {
+    public synchronized byte[] getEncoded() {
         return key.clone();
     }
 
@@ -202,7 +202,7 @@
         return iterCount;
     }
 
-    public char[] getPassword() {
+    public synchronized char[] getPassword() {
         return passwd.clone();
     }
 
@@ -264,13 +264,15 @@
      */
     protected void finalize() throws Throwable {
         try {
-            if (this.passwd != null) {
-                java.util.Arrays.fill(this.passwd, '0');
-                this.passwd = null;
-            }
-            if (this.key != null) {
-                java.util.Arrays.fill(this.key, (byte)0x00);
-                this.key = null;
+            synchronized (this) {
+                if (this.passwd != null) {
+                    java.util.Arrays.fill(this.passwd, '0');
+                    this.passwd = null;
+                }
+                if (this.key != null) {
+                    java.util.Arrays.fill(this.key, (byte)0x00);
+                    this.key = null;
+                }
             }
         } finally {
             super.finalize();
--- a/src/share/classes/com/sun/crypto/provider/SunJCE.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/com/sun/crypto/provider/SunJCE.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, 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
@@ -762,6 +762,8 @@
                         "com.sun.crypto.provider.TlsMasterSecretGenerator");
                     put("Alg.Alias.KeyGenerator.SunTls12MasterSecret",
                         "SunTlsMasterSecret");
+                    put("Alg.Alias.KeyGenerator.SunTlsExtendedMasterSecret",
+                        "SunTlsMasterSecret");
 
                     put("KeyGenerator.SunTlsKeyMaterial",
                         "com.sun.crypto.provider.TlsKeyMaterialGenerator");
--- a/src/share/classes/com/sun/crypto/provider/TlsMasterSecretGenerator.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/com/sun/crypto/provider/TlsMasterSecretGenerator.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2017, 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
@@ -100,21 +100,32 @@
 
         try {
             byte[] master;
-            byte[] clientRandom = spec.getClientRandom();
-            byte[] serverRandom = spec.getServerRandom();
-
             if (protocolVersion >= 0x0301) {
-                byte[] seed = concat(clientRandom, serverRandom);
+                byte[] label;
+                byte[] seed;
+                byte[] extendedMasterSecretSessionHash =
+                        spec.getExtendedMasterSecretSessionHash();
+                if (extendedMasterSecretSessionHash.length != 0) {
+                    label = LABEL_EXTENDED_MASTER_SECRET;
+                    seed = extendedMasterSecretSessionHash;
+                } else {
+                    byte[] clientRandom = spec.getClientRandom();
+                    byte[] serverRandom = spec.getServerRandom();
+                    label = LABEL_MASTER_SECRET;
+                    seed = concat(clientRandom, serverRandom);
+                }
                 master = ((protocolVersion >= 0x0303) ?
-                    doTLS12PRF(premaster, LABEL_MASTER_SECRET, seed, 48,
-                        spec.getPRFHashAlg(), spec.getPRFHashLength(),
-                        spec.getPRFBlockSize()) :
-                    doTLS10PRF(premaster, LABEL_MASTER_SECRET, seed, 48));
+                        doTLS12PRF(premaster, label, seed, 48,
+                                spec.getPRFHashAlg(), spec.getPRFHashLength(),
+                                spec.getPRFBlockSize()) :
+                        doTLS10PRF(premaster, label, seed, 48));
             } else {
                 master = new byte[48];
                 MessageDigest md5 = MessageDigest.getInstance("MD5");
                 MessageDigest sha = MessageDigest.getInstance("SHA");
 
+                byte[] clientRandom = spec.getClientRandom();
+                byte[] serverRandom = spec.getServerRandom();
                 byte[] tmp = new byte[20];
                 for (int i = 0; i < 3; i++) {
                     sha.update(SSL3_CONST[i]);
@@ -172,5 +183,5 @@
         }
 
     }
+}
 
-}
--- a/src/share/classes/com/sun/crypto/provider/TlsPrfGenerator.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/com/sun/crypto/provider/TlsPrfGenerator.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2017, 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
@@ -55,6 +55,11 @@
     final static byte[] LABEL_MASTER_SECRET = // "master secret"
         { 109, 97, 115, 116, 101, 114, 32, 115, 101, 99, 114, 101, 116 };
 
+    final static byte[] LABEL_EXTENDED_MASTER_SECRET =
+                                            // "extended master secret"
+        { 101, 120, 116, 101, 110, 100, 101, 100, 32, 109, 97, 115, 116,
+          101, 114, 32, 115, 101, 99, 114, 101, 116 };
+
     final static byte[] LABEL_KEY_EXPANSION = // "key expansion"
         { 107, 101, 121, 32, 101, 120, 112, 97, 110, 115, 105, 111, 110 };
 
--- a/src/share/classes/com/sun/jmx/remote/internal/RMIExporter.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/com/sun/jmx/remote/internal/RMIExporter.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, 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
@@ -25,6 +25,7 @@
 
 package com.sun.jmx.remote.internal;
 
+import sun.misc.ObjectInputFilter;
 import java.rmi.NoSuchObjectException;
 import java.rmi.Remote;
 import java.rmi.RemoteException;
@@ -51,7 +52,8 @@
     public Remote exportObject(Remote obj,
                                int port,
                                RMIClientSocketFactory csf,
-                               RMIServerSocketFactory ssf)
+                               RMIServerSocketFactory ssf,
+                               ObjectInputFilter filter)
             throws RemoteException;
 
     public boolean unexportObject(Remote obj, boolean force)
--- a/src/share/classes/com/sun/jmx/remote/util/EnvHelp.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/com/sun/jmx/remote/util/EnvHelp.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,6 +1,6 @@
 
 /*
- * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, 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
@@ -70,6 +70,61 @@
             "jmx.remote.rmi.server.credential.types";
 
     /**
+    * Name of the attribute that specifies an
+    * {@link ObjectInputFilter} pattern string to filter classes acceptable
+    * for {@link RMIServer#newClient(java.lang.Object) RMIServer.newClient()}
+    * remote method call.
+    * <p>
+    * The filter pattern must be in same format as used in
+    * {@link java.io.ObjectInputFilter.Config.createFilter}
+    * <p>
+    * This list of classes allowed by filter should correspond to the
+    * transitive closure of the credentials class (or classes) used by the
+    * installed {@linkplain JMXAuthenticator} associated with the
+    * {@linkplain RMIServer} implementation.
+    * If the attribute is not set then any class is deemed acceptable.
+    * @see ObjectInputFilter
+    */
+    public static final String CREDENTIALS_FILTER_PATTERN =
+        "jmx.remote.rmi.server.credentials.filter.pattern";
+
+    /**
+     * This attribute defines a pattern from which to create a
+     * {@link java.io.ObjectInputFilter} that will be used when deserializing
+     * objects sent to the {@code JMXConnectorServer} by any client.
+     * <p>
+     * The filter will be called for any class found in the serialized
+     * stream sent to server by client, including all JMX defined classes
+     * (such as {@link javax.management.ObjectName}), all method parameters,
+     * and, if present in the stream, all classes transitively referred by
+     * the serial form of any deserialized object.
+     * The pattern must be in same format as used in
+     * {@link java.io.ObjectInputFilter.Config.createFilter}.
+     * It may define a white list of permitted classes, a black list of
+     * rejected classes, a maximum depth for the deserialized objects,
+     * etc.
+     * <p>
+     * To be functional, the filter should allow at least all the
+     * concrete types in the transitive closure of all objects that
+     * might get serialized when serializing all JMX classes referred
+     * as parameters in the {@link
+     * javax.management.remote.rmi.RMIConnection} interface,
+     * plus all classes that a {@link javax.management.remote.rmi.RMIConnectorClient}
+     * might need to transmit wrapped in {@linkplain java.rmi.MarshalledObject
+     * marshalled objects} in order to interoperate with the MBeans registered
+     * in the {@code MBeanServer}. That would potentially include all the
+     * concrete {@linkplain javax.management.openmbean  JMX OpenTypes} and the
+     * classes they use in their serial form.
+     * <p>
+     * Care must be taken when defining such a filter, as defining
+     * a white list too restrictive or a too wide a black list may
+     * prevent legitimate clients from interoperating with the
+     * {@code JMXConnectorServer}.
+     */
+    public static final String SERIAL_FILTER_PATTERN =
+       "jmx.remote.rmi.server.serial.filter.pattern";
+
+    /**
      * <p>Name of the attribute that specifies a default class loader
      * object.
      * The value associated with this attribute is a ClassLoader object</p>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/jndi/dns/DNSDatagramSocketFactory.java	Tue Jan 16 22:58:44 2018 -0800
@@ -0,0 +1,246 @@
+/*
+ * Copyright (c) 2017, 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * 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.
+ */
+package com.sun.jndi.dns;
+
+import java.io.IOException;
+import java.net.DatagramSocket;
+import java.net.ProtocolFamily;
+import java.net.SocketException;
+import java.net.InetSocketAddress;
+import java.nio.channels.DatagramChannel;
+import java.util.Objects;
+import java.util.Random;
+
+class DNSDatagramSocketFactory {
+    static final int DEVIATION = 3;
+    static final int THRESHOLD = 6;
+    static final int BIT_DEVIATION = 2;
+    static final int HISTORY = 32;
+    static final int MAX_RANDOM_TRIES = 5;
+    /**
+     * The dynamic allocation port range (aka ephemeral ports), as configured
+     * on the system. Use nested class for lazy evaluation.
+     */
+    static final class EphemeralPortRange {
+        private EphemeralPortRange() {}
+        static final int LOWER = sun.net.PortConfig.getLower();
+        static final int UPPER = sun.net.PortConfig.getUpper();
+        static final int RANGE = UPPER - LOWER + 1;
+    }
+
+    // Records a subset of max {@code capacity} previously used ports
+    static final class PortHistory {
+        final int capacity;
+        final int[] ports;
+        final Random random;
+        int index;
+        PortHistory(int capacity, Random random) {
+            this.random = random;
+            this.capacity = capacity;
+            this.ports = new int[capacity];
+        }
+        // returns true if the history contains the specified port.
+        public boolean contains(int port) {
+            int p = 0;
+            for (int i=0; i<capacity; i++) {
+                if ((p = ports[i]) == 0 || p == port) break;
+            }
+            return p == port;
+        }
+        // Adds the port to the history - doesn't check whether the port
+        // is already present. Always adds the port and always return true.
+        public boolean add(int port) {
+            if (ports[index] != 0) { // at max capacity
+                // remove one port at random and store the new port there
+                ports[random.nextInt(capacity)] = port;
+            } else { // there's a free slot
+                ports[index] = port;
+            }
+            if (++index == capacity) index = 0;
+            return true;
+        }
+        // Adds the port to the history if not already present.
+        // Return true if the port was added, false if the port was already
+        // present.
+        public boolean offer(int port) {
+            if (contains(port)) return false;
+            else return add(port);
+        }
+    }
+
+    int lastport = 0;
+    int suitablePortCount;
+    int unsuitablePortCount;
+    final ProtocolFamily family; // null (default) means dual stack
+    final int thresholdCount; // decision point
+    final int deviation;
+    final Random random;
+    final PortHistory history;
+
+    DNSDatagramSocketFactory() {
+        this(new Random());
+    }
+
+    DNSDatagramSocketFactory(Random random) {
+        this(Objects.requireNonNull(random), null, DEVIATION, THRESHOLD);
+    }
+    DNSDatagramSocketFactory(Random random,
+                             ProtocolFamily family,
+                             int deviation,
+                             int threshold) {
+        this.random = Objects.requireNonNull(random);
+        this.history = new PortHistory(HISTORY, random);
+        this.family = family;
+        this.deviation = Math.max(1, deviation);
+        this.thresholdCount = Math.max(2, threshold);
+    }
+
+    /**
+     * Opens a datagram socket listening to the wildcard address on a
+     * random port. If the underlying OS supports UDP port randomization
+     * out of the box (if binding a socket to port 0 binds it to a random
+     * port) then the underlying OS implementation is used. Otherwise, this
+     * method will allocate and bind a socket on a randomly selected ephemeral
+     * port in the dynamic range.
+     * @return A new DatagramSocket bound to a random port.
+     * @throws SocketException if the socket cannot be created.
+     */
+    public synchronized DatagramSocket open() throws SocketException {
+        int lastseen = lastport;
+        DatagramSocket s;
+
+        boolean thresholdCrossed = unsuitablePortCount > thresholdCount;
+        if (thresholdCrossed) {
+            // Underlying stack does not support random UDP port out of the box.
+            // Use our own algorithm to allocate a random UDP port
+            s = openRandom();
+            if (s != null) return s;
+
+            // couldn't allocate a random port: reset all counters and fall
+            // through.
+            unsuitablePortCount = 0; suitablePortCount = 0; lastseen = 0;
+        }
+
+        // Allocate an ephemeral port (port 0)
+        s = openDefault();
+        lastport = s.getLocalPort();
+        if (lastseen == 0) {
+            history.offer(lastport);
+            return s;
+        }
+
+        thresholdCrossed = suitablePortCount > thresholdCount;
+        boolean farEnough = Integer.bitCount(lastseen ^ lastport) > BIT_DEVIATION
+                            && Math.abs(lastport - lastseen) > deviation;
+        boolean recycled = history.contains(lastport);
+        boolean suitable = (thresholdCrossed || farEnough && !recycled);
+        if (suitable && !recycled) history.add(lastport);
+
+        if (suitable) {
+            if (!thresholdCrossed) {
+                suitablePortCount++;
+            } else if (!farEnough || recycled) {
+                unsuitablePortCount = 1;
+                suitablePortCount = thresholdCount/2;
+            }
+            // Either the underlying stack supports random UDP port allocation,
+            // or the new port is sufficiently distant from last port to make
+            // it look like it is. Let's use it.
+            return s;
+        }
+
+        // Undecided... the new port was too close. Let's allocate a random
+        // port using our own algorithm
+        assert !thresholdCrossed;
+        DatagramSocket ss = openRandom();
+        if (ss == null) return s;
+        unsuitablePortCount++;
+        s.close();
+        return ss;
+    }
+
+    private DatagramSocket openDefault() throws SocketException {
+        if (family != null) {
+            try {
+                DatagramChannel c = DatagramChannel.open(family);
+                try {
+                    DatagramSocket s = c.socket();
+                    s.bind(null);
+                    return s;
+                } catch (Throwable x) {
+                    c.close();
+                    throw x;
+                }
+            } catch (SocketException x) {
+                throw x;
+            } catch (IOException x) {
+                SocketException e = new SocketException(x.getMessage());
+                e.initCause(x);
+                throw e;
+            }
+        }
+        return new DatagramSocket();
+    }
+
+    synchronized boolean isUsingNativePortRandomization() {
+        return  unsuitablePortCount <= thresholdCount
+                && suitablePortCount > thresholdCount;
+    }
+
+    synchronized boolean isUsingJavaPortRandomization() {
+        return unsuitablePortCount > thresholdCount ;
+    }
+
+    synchronized boolean isUndecided() {
+        return !isUsingJavaPortRandomization()
+                && !isUsingNativePortRandomization();
+    }
+
+    private DatagramSocket openRandom() {
+        int maxtries = MAX_RANDOM_TRIES;
+        while (maxtries-- > 0) {
+            int port = EphemeralPortRange.LOWER
+                    + random.nextInt(EphemeralPortRange.RANGE);
+            try {
+                if (family != null) {
+                    DatagramChannel c = DatagramChannel.open(family);
+                    try {
+                        DatagramSocket s = c.socket();
+                        s.bind(new InetSocketAddress(port));
+                        return s;
+                    } catch (Throwable x) {
+                        c.close();
+                        throw x;
+                    }
+                }
+                return new DatagramSocket(port);
+            } catch (IOException x) {
+                // try again until maxtries == 0;
+            }
+        }
+        return null;
+    }
+
+}
--- a/src/share/classes/com/sun/jndi/dns/DnsClient.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/com/sun/jndi/dns/DnsClient.java	Tue Jan 16 22:58:44 2018 -0800
@@ -85,7 +85,9 @@
     private int timeout;                // initial timeout on UDP queries in ms
     private int retries;                // number of UDP retries
 
-    private DatagramSocket udpSocket;
+    private final Object udpSocketLock = new Object();
+    private static final DNSDatagramSocketFactory factory =
+            new DNSDatagramSocketFactory(random);
 
     // Requests sent
     private Map<Integer, ResourceRecord> reqs;
@@ -105,14 +107,6 @@
             throws NamingException {
         this.timeout = timeout;
         this.retries = retries;
-        try {
-            udpSocket = new DatagramSocket();
-        } catch (java.net.SocketException e) {
-            NamingException ne = new ConfigurationException();
-            ne.setRootCause(e);
-            throw ne;
-        }
-
         this.servers = new InetAddress[servers.length];
         serverPorts = new int[servers.length];
 
@@ -142,6 +136,16 @@
         resps = Collections.synchronizedMap(new HashMap<Integer, byte[]>());
     }
 
+    DatagramSocket getDatagramSocket() throws NamingException {
+        try {
+            return factory.open();
+        } catch (java.net.SocketException e) {
+            NamingException ne = new ConfigurationException();
+            ne.setRootCause(e);
+            throw ne;
+        }
+    }
+
     protected void finalize() {
         close();
     }
@@ -150,7 +154,6 @@
     private Object queuesLock = new Object();
 
     public void close() {
-        udpSocket.close();
         synchronized (queuesLock) {
             reqs.clear();
             resps.clear();
@@ -392,44 +395,45 @@
 
         int minTimeout = 50; // msec after which there are no retries.
 
-        synchronized (udpSocket) {
-            DatagramPacket opkt = new DatagramPacket(
-                    pkt.getData(), pkt.length(), server, port);
-            DatagramPacket ipkt = new DatagramPacket(new byte[8000], 8000);
-            // Packets may only be sent to or received from this server address
-            udpSocket.connect(server, port);
-            int pktTimeout = (timeout * (1 << retry));
-            try {
-                udpSocket.send(opkt);
+        synchronized (udpSocketLock) {
+            try (DatagramSocket udpSocket = getDatagramSocket()) {
+                DatagramPacket opkt = new DatagramPacket(
+                        pkt.getData(), pkt.length(), server, port);
+                DatagramPacket ipkt = new DatagramPacket(new byte[8000], 8000);
+                // Packets may only be sent to or received from this server address
+                udpSocket.connect(server, port);
+                int pktTimeout = (timeout * (1 << retry));
+                try {
+                    udpSocket.send(opkt);
 
-                // timeout remaining after successive 'receive()'
-                int timeoutLeft = pktTimeout;
-                int cnt = 0;
-                do {
-                    if (debug) {
-                       cnt++;
-                        dprint("Trying RECEIVE(" +
-                                cnt + ") retry(" + (retry + 1) +
-                                ") for:" + xid  + "    sock-timeout:" +
-                                timeoutLeft + " ms.");
-                    }
-                    udpSocket.setSoTimeout(timeoutLeft);
-                    long start = System.currentTimeMillis();
-                    udpSocket.receive(ipkt);
-                    long end = System.currentTimeMillis();
+                    // timeout remaining after successive 'receive()'
+                    int timeoutLeft = pktTimeout;
+                    int cnt = 0;
+                    do {
+                        if (debug) {
+                           cnt++;
+                            dprint("Trying RECEIVE(" +
+                                    cnt + ") retry(" + (retry + 1) +
+                                    ") for:" + xid  + "    sock-timeout:" +
+                                    timeoutLeft + " ms.");
+                        }
+                        udpSocket.setSoTimeout(timeoutLeft);
+                        long start = System.currentTimeMillis();
+                        udpSocket.receive(ipkt);
+                        long end = System.currentTimeMillis();
 
-                    byte[] data = new byte[ipkt.getLength()];
-                    data = ipkt.getData();
-                    if (isMatchResponse(data, xid)) {
-                        return data;
-                    }
-                    timeoutLeft = pktTimeout - ((int) (end - start));
-                } while (timeoutLeft > minTimeout);
+                        byte[] data = ipkt.getData();
+                        if (isMatchResponse(data, xid)) {
+                            return data;
+                        }
+                        timeoutLeft = pktTimeout - ((int) (end - start));
+                    } while (timeoutLeft > minTimeout);
 
-            } finally {
-                udpSocket.disconnect();
+                } finally {
+                    udpSocket.disconnect();
+                }
+                return null; // no matching packet received within the timeout
             }
-            return null; // no matching packet received within the timeout
         }
     }
 
--- a/src/share/classes/com/sun/jndi/dns/ResourceRecord.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/com/sun/jndi/dns/ResourceRecord.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2002, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2017, 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
@@ -25,8 +25,13 @@
 
 package com.sun.jndi.dns;
 
+import javax.naming.CommunicationException;
 import javax.naming.InvalidNameException;
 
+import java.io.IOException;
+
+import java.nio.charset.StandardCharsets;
+
 
 /**
  * The ResourceRecord class represents a DNS resource record.
@@ -84,6 +89,11 @@
         null, "IN", null, null, "HS"
     };
 
+    /*
+     * Maximum number of compression references in labels.
+     * Used to detect compression loops.
+     */
+    private static final int MAXIMUM_COMPRESSION_REFERENCES = 16;
 
     byte[] msg;                 // DNS message
     int msgLen;                 // msg size (in octets)
@@ -110,12 +120,12 @@
      * false, the rdata is not decoded (and getRdata() will return null)
      * unless this is an SOA record.
      *
-     * @throws InvalidNameException if a decoded domain name isn't valid.
+     * @throws CommunicationException if a decoded domain name isn't valid.
      * @throws ArrayIndexOutOfBoundsException given certain other corrupt data.
      */
     ResourceRecord(byte[] msg, int msgLen, int offset,
                    boolean qSection, boolean decodeRdata)
-            throws InvalidNameException {
+            throws CommunicationException {
 
         this.msg = msg;
         this.msgLen = msgLen;
@@ -235,7 +245,7 @@
      * Decodes the binary format of the RR.
      * May throw ArrayIndexOutOfBoundsException given corrupt data.
      */
-    private void decode(boolean decodeRdata) throws InvalidNameException {
+    private void decode(boolean decodeRdata) throws CommunicationException {
         int pos = offset;       // index of next unread octet
 
         name = new DnsName();                           // NAME
@@ -316,7 +326,7 @@
     /*
      * Returns the name encoded at msg[pos], including the root label.
      */
-    private DnsName decodeName(int pos) throws InvalidNameException {
+    private DnsName decodeName(int pos) throws CommunicationException {
         DnsName n = new DnsName();
         decodeName(pos, n);
         return n;
@@ -326,22 +336,50 @@
      * Prepends to "n" the domain name encoded at msg[pos], including the root
      * label.  Returns the index into "msg" following the name.
      */
-    private int decodeName(int pos, DnsName n) throws InvalidNameException {
-        if (msg[pos] == 0) {                            // end of name
-            n.add(0, "");
-            return (pos + 1);
-        } else if ((msg[pos] & 0xC0) != 0) {            // name compression
-            decodeName(getUShort(pos) & 0x3FFF, n);
-            return (pos + 2);
-        } else {                                        // append a label
-            int len = msg[pos++];
-            try {
-                n.add(0, new String(msg, pos, len, "ISO-8859-1"));
-            } catch (java.io.UnsupportedEncodingException e) {
-                // assert false : "ISO-Latin-1 charset unavailable";
+    private int decodeName(int pos, DnsName n) throws CommunicationException {
+        int endPos = -1;
+        int level = 0;
+        try {
+            while (true) {
+                if (level > MAXIMUM_COMPRESSION_REFERENCES)
+                    throw new IOException("Too many compression references");
+                int typeAndLen = msg[pos] & 0xFF;
+                if (typeAndLen == 0) {                  // end of name
+                    ++pos;
+                    n.add(0, "");
+                    break;
+                } else if (typeAndLen <= 63) {          // regular label
+                    ++pos;
+                    n.add(0, new String(msg, pos, typeAndLen,
+                        StandardCharsets.ISO_8859_1));
+                    pos += typeAndLen;
+                } else if ((typeAndLen & 0xC0) == 0xC0) { // name compression
+                    ++level;
+                    // cater for the case where the name pointed to is itself
+                    // compressed: we don't want endPos to be reset by the second
+                    // compression level.
+                    int ppos = pos;
+                    if (endPos == -1) endPos = pos + 2;
+                    pos = getUShort(pos) & 0x3FFF;
+                    if (debug) {
+                        dprint("decode: name compression at " + ppos
+                                + " -> " + pos + " endPos=" + endPos);
+                        assert endPos > 0;
+                        assert pos < ppos;
+                        assert pos >= Header.HEADER_SIZE;
+                    }
+                } else
+                    throw new IOException("Invalid label type: " + typeAndLen);
             }
-            return decodeName(pos + len, n);
+        } catch (IOException | InvalidNameException e) {
+            CommunicationException ce =new CommunicationException(
+                "DNS error: malformed packet");
+            ce.initCause(e);
+            throw ce;
         }
+        if (endPos == -1)
+            endPos = pos;
+        return endPos;
     }
 
     /*
@@ -352,7 +390,7 @@
      * The rdata of records with unknown type/class combinations is
      * returned in a newly-allocated byte array.
      */
-    private Object decodeRdata(int pos) throws InvalidNameException {
+    private Object decodeRdata(int pos) throws CommunicationException {
         if (rrclass == CLASS_INTERNET) {
             switch (rrtype) {
             case TYPE_A:
@@ -378,6 +416,11 @@
             }
         }
         // Unknown RR type/class
+        if (debug) {
+            dprint("Unknown RR type for RR data: " + rrtype + " rdlen=" + rdlen
+                   + ", pos=" + pos +", msglen=" + msg.length + ", remaining="
+                   + (msg.length-pos));
+        }
         byte[] rd = new byte[rdlen];
         System.arraycopy(msg, pos, rd, 0, rdlen);
         return rd;
@@ -386,7 +429,7 @@
     /*
      * Returns the rdata of an MX record that is encoded at msg[pos].
      */
-    private String decodeMx(int pos) throws InvalidNameException {
+    private String decodeMx(int pos) throws CommunicationException {
         int preference = getUShort(pos);
         pos += 2;
         DnsName name = decodeName(pos);
@@ -396,7 +439,7 @@
     /*
      * Returns the rdata of an SOA record that is encoded at msg[pos].
      */
-    private String decodeSoa(int pos) throws InvalidNameException {
+    private String decodeSoa(int pos) throws CommunicationException {
         DnsName mname = new DnsName();
         pos = decodeName(pos, mname);
         DnsName rname = new DnsName();
@@ -421,7 +464,7 @@
      * Returns the rdata of an SRV record that is encoded at msg[pos].
      * See RFC 2782.
      */
-    private String decodeSrv(int pos) throws InvalidNameException {
+    private String decodeSrv(int pos) throws CommunicationException {
         int priority = getUShort(pos);
         pos += 2;
         int weight =   getUShort(pos);
@@ -436,7 +479,7 @@
      * Returns the rdata of an NAPTR record that is encoded at msg[pos].
      * See RFC 2915.
      */
-    private String decodeNaptr(int pos) throws InvalidNameException {
+    private String decodeNaptr(int pos) throws CommunicationException {
         int order = getUShort(pos);
         pos += 2;
         int preference = getUShort(pos);
@@ -586,4 +629,15 @@
 
         return buf.toString();
     }
+
+    //-------------------------------------------------------------------------
+
+    private static final boolean debug = false;
+
+    private static void dprint(String mess) {
+        if (debug) {
+            System.err.println("DNS: " + mess);
+        }
+    }
+
 }
--- a/src/share/classes/com/sun/rowset/RowSetResourceBundle_sv.properties	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/com/sun/rowset/RowSetResourceBundle_sv.properties	Tue Jan 16 22:58:44 2018 -0800
@@ -159,8 +159,8 @@
 xmlrch.errupdate = Ett fel intr\u00E4ffade vid konstruktion av uppdateringsrad: {0}
 xmlrch.errupdrow = Ett fel intr\u00E4ffade vid uppdatering av rad: {0}
 xmlrch.chars = tecken:
-xmlrch.badvalue = Felaktigt v\u00E4rde; egenskapen kan inte ha ett tomt v\u00E4rde
-xmlrch.badvalue1 = Felaktigt v\u00E4rde; metadatan kan inte ha ett tomt v\u00E4rde
+xmlrch.badvalue = Felaktigt v\u00E4rde; egenskapen f\u00E5r inte ha v\u00E4rdet null
+xmlrch.badvalue1 = Felaktigt v\u00E4rde; metadata f\u00E5r inte ha v\u00E4rdet null
 xmlrch.warning =  ** Varning! {0}, rad: {1}, URI: {2}
 
 #RIOptimisticProvider Exceptions
--- a/src/share/classes/com/sun/security/auth/module/LdapLoginModule.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/com/sun/security/auth/module/LdapLoginModule.java	Tue Jan 16 22:58:44 2018 -0800
@@ -751,7 +751,8 @@
 
         if (authFirst || authOnly) {
 
-            String id = replaceUsernameToken(identityMatcher, authcIdentity);
+            String id =
+                replaceUsernameToken(identityMatcher, authcIdentity, username);
 
             // Prepare to bind using user's username and password
             ldapEnvironment.put(Context.SECURITY_CREDENTIALS, password);
@@ -878,8 +879,13 @@
         }
 
         try {
-            NamingEnumeration<SearchResult> results = ctx.search("",
-                replaceUsernameToken(filterMatcher, userFilter), constraints);
+            // Sanitize username and substitute into LDAP filter
+            String canonicalUserFilter =
+                replaceUsernameToken(filterMatcher, userFilter,
+                    escapeUsernameChars());
+
+            NamingEnumeration<SearchResult> results =
+                ctx.search("", canonicalUserFilter, constraints);
 
             // Extract the distinguished name of the user's entry
             // (Use the first entry if more than one is returned)
@@ -927,12 +933,61 @@
     }
 
     /**
+     * Modify the supplied username to encode characters that must be escaped
+     * according to RFC 4515: LDAP: String Representation of Search Filters.
+     *
+     * The following characters are encoded as a backslash "\" (ASCII 0x5c)
+     * followed by the two hexadecimal digits representing the value of the
+     * escaped character:
+     *     '*' (ASCII 0x2a)
+     *     '(' (ASCII 0x28)
+     *     ')' (ASCII 0x29)
+     *     '\' (ASCII 0x5c)
+     *     '\0'(ASCII 0x00)
+     *
+     * @return the modified username with its characters escaped as needed
+     */
+    private String escapeUsernameChars() {
+        int len = username.length();
+        StringBuilder escapedUsername = new StringBuilder(len + 16);
+
+        for (int i = 0; i < len; i++) {
+            char c = username.charAt(i);
+            switch (c) {
+            case '*':
+                escapedUsername.append("\\\\2A");
+                break;
+            case '(':
+                escapedUsername.append("\\\\28");
+                break;
+            case ')':
+                escapedUsername.append("\\\\29");
+                break;
+            case '\\':
+                escapedUsername.append("\\\\5C");
+                break;
+            case '\0':
+                escapedUsername.append("\\\\00");
+                break;
+            default:
+                escapedUsername.append(c);
+            }
+        }
+
+        return escapedUsername.toString();
+    }
+
+
+    /**
      * Replace the username token
      *
+     * @param matcher the replacement pattern
      * @param string the target string
+     * @param username the supplied username
      * @return the modified string
      */
-    private String replaceUsernameToken(Matcher matcher, String string) {
+    private String replaceUsernameToken(Matcher matcher, String string,
+        String username) {
         return matcher != null ? matcher.replaceAll(username) : string;
     }
 
--- a/src/share/classes/java/awt/Toolkit.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/java/awt/Toolkit.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1995, 2017, 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
@@ -1656,7 +1656,9 @@
                 try {
                     resources =
                         ResourceBundle.getBundle("sun.awt.resources.awt",
-                                                 CoreResourceBundleControl.getRBControlInstance());
+                                Locale.getDefault(),
+                                ClassLoader.getSystemClassLoader(),
+                                CoreResourceBundleControl.getRBControlInstance());
                 } catch (MissingResourceException e) {
                     // No resource file; defaults will be used.
                 }
--- a/src/share/classes/java/awt/Window.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/java/awt/Window.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1995, 2017, 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
@@ -2786,7 +2786,9 @@
      */
     @Deprecated
     public void applyResourceBundle(String rbName) {
-        applyResourceBundle(ResourceBundle.getBundle(rbName));
+        applyResourceBundle(ResourceBundle.getBundle(rbName,
+                                Locale.getDefault(),
+                                ClassLoader.getSystemClassLoader()));
     }
 
    /*
--- a/src/share/classes/java/awt/color/ICC_ColorSpace.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/java/awt/color/ICC_ColorSpace.java	Tue Jan 16 22:58:44 2018 -0800
@@ -128,6 +128,18 @@
     }
 
     /**
+     * Validate ICC_ColorSpace read from an object input stream
+     */
+    private void readObject(java.io.ObjectInputStream s)
+        throws ClassNotFoundException, java.io.IOException {
+
+        s.defaultReadObject();
+        if (thisProfile == null) {
+            thisProfile = ICC_Profile.getInstance(ColorSpace.CS_sRGB);
+        }
+    }
+
+    /**
     * Returns the ICC_Profile for this ICC_ColorSpace.
     * @return the ICC_Profile for this ICC_ColorSpace.
     */
--- a/src/share/classes/java/awt/geom/Path2D.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/java/awt/geom/Path2D.java	Tue Jan 16 22:58:44 2018 -0800
@@ -25,13 +25,14 @@
 
 package java.awt.geom;
 
+import java.awt.Rectangle;
 import java.awt.Shape;
-import java.awt.Rectangle;
-import sun.awt.geom.Curve;
 import java.io.Serializable;
 import java.io.StreamCorruptedException;
 import java.util.Arrays;
 
+import sun.awt.geom.Curve;
+
 /**
  * The {@code Path2D} class provides a simple, yet flexible
  * shape which represents an arbitrary geometric path.
@@ -2583,9 +2584,12 @@
             throw new java.io.InvalidObjectException(iae.getMessage());
         }
 
-        pointTypes = new byte[(nT < 0) ? INIT_SIZE : nT];
-        if (nC < 0) {
-            nC = INIT_SIZE * 2;
+        // Accept the size from the stream only if it is less than INIT_SIZE
+        // otherwise the size will be based on the real data in the stream
+        pointTypes = new byte[(nT < 0 || nT > INIT_SIZE) ? INIT_SIZE : nT];
+        final int initX2 = INIT_SIZE * 2;
+        if (nC < 0 || nC > initX2) {
+            nC = initX2;
         }
         if (storedbl) {
             ((Path2D.Double) this).doubleCoords = new double[nC];
--- a/src/share/classes/java/io/ObjectInputStream.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/java/io/ObjectInputStream.java	Tue Jan 16 22:58:44 2018 -0800
@@ -45,7 +45,6 @@
 
 import sun.misc.SharedSecrets;
 import sun.misc.ObjectInputFilter;
-import sun.misc.ObjectStreamClassValidator;
 import sun.reflect.misc.ReflectUtil;
 import sun.misc.JavaOISAccess;
 import sun.util.logging.PlatformLogger;
@@ -1749,9 +1748,6 @@
                 throw new StreamCorruptedException(
                     String.format("invalid type code: %02X", tc));
         }
-        if (descriptor != null) {
-            validateDescriptor(descriptor);
-        }
         return descriptor;
     }
 
@@ -3896,21 +3892,4 @@
             throw new AssertionError();
         }
     }
-
-    private void validateDescriptor(ObjectStreamClass descriptor) {
-        ObjectStreamClassValidator validating = validator;
-        if (validating != null) {
-            validating.validateDescriptor(descriptor);
-        }
-    }
-
-    // controlled access to ObjectStreamClassValidator
-    private volatile ObjectStreamClassValidator validator;
-
-    private static void setValidator(ObjectInputStream ois, ObjectStreamClassValidator validator) {
-        ois.validator = validator;
-    }
-    static {
-        SharedSecrets.setJavaObjectInputStreamAccess(ObjectInputStream::setValidator);
-    }
 }
--- a/src/share/classes/java/lang/invoke/DirectMethodHandle.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/java/lang/invoke/DirectMethodHandle.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2017, 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
@@ -75,13 +75,20 @@
             mtype = mtype.insertParameterTypes(0, receiver);
         }
         if (!member.isField()) {
-            if (refKind == REF_invokeSpecial) {
-                member = member.asSpecial();
-                LambdaForm lform = preparedLambdaForm(member);
-                return new Special(mtype, lform, member);
-            } else {
-                LambdaForm lform = preparedLambdaForm(member);
-                return new DirectMethodHandle(mtype, lform, member);
+            switch (refKind) {
+                case REF_invokeSpecial: {
+                    member = member.asSpecial();
+                    LambdaForm lform = preparedLambdaForm(member);
+                    return new Special(mtype, lform, member);
+                }
+                case REF_invokeInterface: {
+                    LambdaForm lform = preparedLambdaForm(member);
+                    return new Interface(mtype, lform, member, receiver);
+                }
+                default: {
+                    LambdaForm lform = preparedLambdaForm(member);
+                    return new DirectMethodHandle(mtype, lform, member);
+                }
             }
         } else {
             LambdaForm lform = preparedFieldLambdaForm(member);
@@ -191,6 +198,7 @@
     private static LambdaForm makePreparedLambdaForm(MethodType mtype, int which) {
         boolean needsInit = (which == LF_INVSTATIC_INIT);
         boolean doesAlloc = (which == LF_NEWINVSPECIAL);
+        boolean needsReceiverCheck = (which == LF_INVINTERFACE);
         String linkerName, lambdaName;
         switch (which) {
         case LF_INVVIRTUAL:    linkerName = "linkToVirtual";    lambdaName = "DMH.invokeVirtual";    break;
@@ -218,6 +226,7 @@
         int nameCursor = ARG_LIMIT;
         final int NEW_OBJ     = (doesAlloc ? nameCursor++ : -1);
         final int GET_MEMBER  = nameCursor++;
+        final int CHECK_RECEIVER = (needsReceiverCheck ? nameCursor++ : -1);
         final int LINKER_CALL = nameCursor++;
         Name[] names = arguments(nameCursor - ARG_LIMIT, mtype.invokerType());
         assert(names.length == nameCursor);
@@ -232,6 +241,10 @@
         }
         assert(findDirectMethodHandle(names[GET_MEMBER]) == names[DMH_THIS]);
         Object[] outArgs = Arrays.copyOfRange(names, ARG_BASE, GET_MEMBER+1, Object[].class);
+        if (needsReceiverCheck) {
+            names[CHECK_RECEIVER] = new Name(Lazy.NF_checkReceiver, names[DMH_THIS], names[ARG_BASE]);
+            outArgs[0] = names[CHECK_RECEIVER];
+        }
         assert(outArgs[outArgs.length-1] == names[GET_MEMBER]);  // look, shifted args!
         int result = LAST_RESULT;
         if (doesAlloc) {
@@ -375,6 +388,29 @@
         }
     }
 
+    /** This subclass represents invokeinterface instructions. */
+    static class Interface extends DirectMethodHandle {
+        private final Class<?> refc;
+        private Interface(MethodType mtype, LambdaForm form, MemberName member, Class<?> refc) {
+            super(mtype, form, member);
+            assert refc.isInterface() : refc;
+            this.refc = refc;
+        }
+        @Override
+        MethodHandle copyWith(MethodType mt, LambdaForm lf) {
+            return new Interface(mt, lf, member, refc);
+        }
+
+        Object checkReceiver(Object recv) {
+            if (!refc.isInstance(recv)) {
+                String msg = String.format("Class %s does not implement the requested interface %s",
+                        recv.getClass().getName(), refc.getName());
+                throw new IncompatibleClassChangeError(msg);
+            }
+            return recv;
+        }
+    }
+
     /** This subclass handles constructor references. */
     static class Constructor extends DirectMethodHandle {
         final MemberName initMethod;
@@ -657,7 +693,8 @@
                 NF_staticOffset,
                 NF_checkCast,
                 NF_allocateInstance,
-                NF_constructorMethod;
+                NF_constructorMethod,
+                NF_checkReceiver;
         static {
             try {
                 NamedFunction nfs[] = {
@@ -680,7 +717,9 @@
                         NF_allocateInstance = new NamedFunction(DirectMethodHandle.class
                                 .getDeclaredMethod("allocateInstance", Object.class)),
                         NF_constructorMethod = new NamedFunction(DirectMethodHandle.class
-                                .getDeclaredMethod("constructorMethod", Object.class))
+                                .getDeclaredMethod("constructorMethod", Object.class)),
+                        NF_checkReceiver = new NamedFunction(new MemberName(Interface.class
+                                .getDeclaredMethod("checkReceiver", Object.class)))
                 };
                 for (NamedFunction nf : nfs) {
                     // Each nf must be statically invocable or we get tied up in our bootstraps.
--- a/src/share/classes/java/util/ArrayList.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/java/util/ArrayList.java	Tue Jan 16 22:58:44 2018 -0800
@@ -225,7 +225,7 @@
             return Math.max(DEFAULT_CAPACITY, minCapacity);
         }
         return minCapacity;
-        }
+    }
 
     private void ensureCapacityInternal(int minCapacity) {
         ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
--- a/src/share/classes/java/util/HashMap.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/java/util/HashMap.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1398,7 +1398,7 @@
             // what we're actually creating.
             SharedSecrets.getJavaOISAccess().checkArray(s, Map.Entry[].class, cap);
             @SuppressWarnings({"rawtypes","unchecked"})
-                Node<K,V>[] tab = (Node<K,V>[])new Node[cap];
+            Node<K,V>[] tab = (Node<K,V>[])new Node[cap];
             table = tab;
 
             // Read the keys and values, and put the mappings in the HashMap
--- a/src/share/classes/java/util/ResourceBundle.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/java/util/ResourceBundle.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2017, 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
@@ -485,7 +485,7 @@
     }
 
     /**
-     * A wrapper of ClassLoader.getSystemClassLoader().
+     * A wrapper of Extension Class Loader
      */
     private static class RBClassLoader extends ClassLoader {
         private static final RBClassLoader INSTANCE = AccessController.doPrivileged(
@@ -494,7 +494,16 @@
                             return new RBClassLoader();
                         }
                     });
-        private static final ClassLoader loader = ClassLoader.getSystemClassLoader();
+        private static final ClassLoader loader;
+        static {
+            // Find the extension class loader.
+            ClassLoader ld = ClassLoader.getSystemClassLoader();
+            ClassLoader parent;
+            while ((parent = ld.getParent()) != null) {
+                ld = parent;
+            }
+            loader = ld;
+        }
 
         private RBClassLoader() {
         }
--- a/src/share/classes/java/util/concurrent/ArrayBlockingQueue.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/java/util/concurrent/ArrayBlockingQueue.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1414,4 +1414,30 @@
              Spliterator.CONCURRENT);
     }
 
+    /**
+     * Deserializes this queue and then checks some invariants.
+     *
+     * @param s the input stream
+     * @throws ClassNotFoundException if the class of a serialized object
+     *         could not be found
+     * @throws java.io.InvalidObjectException if invariants are violated
+     * @throws java.io.IOException if an I/O error occurs
+     */
+    private void readObject(java.io.ObjectInputStream s)
+        throws java.io.IOException, ClassNotFoundException {
+
+        // Read in items array and various fields
+        s.defaultReadObject();
+
+        // Check invariants over count and index fields. Note that
+        // if putIndex==takeIndex, count can be either 0 or items.length.
+        if (items.length == 0 ||
+            takeIndex < 0 || takeIndex >= items.length ||
+            putIndex  < 0 || putIndex  >= items.length ||
+            count < 0     || count     >  items.length ||
+            Math.floorMod(putIndex - takeIndex, items.length) !=
+            Math.floorMod(count, items.length)) {
+            throw new java.io.InvalidObjectException("invariants violated");
+        }
+    }
 }
--- a/src/share/classes/java/util/logging/Level.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/java/util/logging/Level.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2017, 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
@@ -262,11 +262,17 @@
     }
 
     private String computeLocalizedLevelName(Locale newLocale) {
-        ResourceBundle rb = ResourceBundle.getBundle(resourceBundleName, newLocale);
-        final String localizedName = rb.getString(name);
+        // If this is a custom Level, load resource bundles on the
+        // classpath and return.
+        if (!defaultBundle.equals(resourceBundleName)) {
+            return ResourceBundle.getBundle(resourceBundleName, newLocale,
+                       ClassLoader.getSystemClassLoader()).getString(name);
+        }
 
-        final boolean isDefaultBundle = defaultBundle.equals(resourceBundleName);
-        if (!isDefaultBundle) return localizedName;
+        // The default bundle "sun.util.logging.resources.logging" should only
+        // be loaded from the runtime; so use the extension class loader;
+        final ResourceBundle rb = ResourceBundle.getBundle(defaultBundle, newLocale);
+        final String localizedName = rb.getString(name);
 
         // This is a trick to determine whether the name has been translated
         // or not. If it has not been translated, we need to use Locale.ROOT
--- a/src/share/classes/java/util/logging/Logger.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/java/util/logging/Logger.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2017, 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
@@ -1817,8 +1817,7 @@
             public ResourceBundle run() {
                 try {
                     return ResourceBundle.getBundle(SYSTEM_LOGGER_RB_NAME,
-                                                    locale,
-                                                    ClassLoader.getSystemClassLoader());
+                                                    locale);
                 } catch (MissingResourceException e) {
                     throw new InternalError(e.toString());
                 }
--- a/src/share/classes/javax/management/remote/rmi/RMIConnectorServer.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/javax/management/remote/rmi/RMIConnectorServer.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2017, 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
@@ -33,6 +33,7 @@
 
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
+import sun.misc.ObjectInputFilter;
 import java.io.ObjectOutputStream;
 import java.net.MalformedURLException;
 import java.rmi.server.RMIClientSocketFactory;
--- a/src/share/classes/javax/management/remote/rmi/RMIJRMPServerImpl.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/javax/management/remote/rmi/RMIJRMPServerImpl.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2017, 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
@@ -26,6 +26,7 @@
 package javax.management.remote.rmi;
 
 import java.io.IOException;
+import sun.misc.ObjectInputFilter;
 import java.rmi.NoSuchObjectException;
 import java.rmi.Remote;
 import java.rmi.RemoteException;
@@ -47,6 +48,11 @@
 import sun.rmi.server.DeserializationChecker;
 import sun.rmi.server.UnicastServerRef;
 import sun.rmi.server.UnicastServerRef2;
+import java.util.Arrays;
+import java.util.Set;
+import java.util.stream.Collectors;
+import sun.rmi.transport.LiveRef;
+
 
 /**
  * <p>An {@link RMIServer} object that is exported through JRMP and that
@@ -59,8 +65,6 @@
  */
 public class RMIJRMPServerImpl extends RMIServerImpl {
 
-    private final ExportedWrapper exportedWrapper;
-
     /**
      * <p>Creates a new {@link RMIServer} object that will be exported
      * on the given port using the given socket factories.</p>
@@ -101,31 +105,37 @@
 
         String[] credentialsTypes
                 = (String[]) this.env.get(EnvHelp.CREDENTIAL_TYPES);
-        List<String> types = null;
-        if (credentialsTypes != null) {
-            types = new ArrayList<>();
-            for (String type : credentialsTypes) {
-                if (type == null) {
-                    throw new IllegalArgumentException("A credential type is null.");
-                }
-                ReflectUtil.checkPackageAccess(type);
-                types.add(type);
-            }
+
+        String credentialsFilter
+                = (String) this.env.get(EnvHelp.CREDENTIALS_FILTER_PATTERN);
+
+        if(credentialsFilter != null){
+            cFilter = ObjectInputFilter.Config.createFilter(credentialsFilter);
+            allowedTypes = null;
         }
-        exportedWrapper = types != null ?
-                new ExportedWrapper(this, types) :
-                null;
+        else if (credentialsTypes != null) {
+            allowedTypes = Arrays.stream(credentialsTypes).filter(
+                    s -> s!= null).collect(Collectors.toSet());
+            allowedTypes.stream().forEach(ReflectUtil::checkPackageAccess);
+            cFilter = this::newClientCheckInput;
+        } else {
+            allowedTypes = null;
+            cFilter = null;
+        }
+
+        String userJmxFilter =
+                (String) this.env.get(EnvHelp.SERIAL_FILTER_PATTERN);
+        if(userJmxFilter != null && !userJmxFilter.isEmpty())
+            jmxRmiFilter = ObjectInputFilter.Config.createFilter(userJmxFilter);
+        else
+            jmxRmiFilter = null;
     }
 
     protected void export() throws IOException {
-        if (exportedWrapper != null) {
-            export(exportedWrapper);
-        } else {
-            export(this);
-        }
+        export(this, cFilter);
     }
 
-    private void export(Remote obj) throws RemoteException {
+    private void export(Remote obj, ObjectInputFilter typeFilter) throws RemoteException {
         final RMIExporter exporter =
             (RMIExporter) env.get(RMIExporter.EXPORTER_ATTRIBUTE);
         final boolean daemon = EnvHelp.isServerDaemon(env);
@@ -136,16 +146,14 @@
                     " cannot be used to specify an exporter!");
         }
 
-        if (daemon) {
+        if (exporter != null) {
+            exporter.exportObject(obj, port, csf, ssf, typeFilter);
+        } else {
             if (csf == null && ssf == null) {
-                new UnicastServerRef(port).exportObject(obj, null, true);
+                new UnicastServerRef(new LiveRef(port), typeFilter).exportObject(obj, null, daemon);
             } else {
-                new UnicastServerRef2(port, csf, ssf).exportObject(obj, null, true);
+                new UnicastServerRef2(port, csf, ssf, typeFilter).exportObject(obj, null, daemon);
             }
-        } else if (exporter != null) {
-            exporter.exportObject(obj, port, csf, ssf);
-        } else {
-            UnicastRemoteObject.exportObject(obj, port, csf, ssf);
         }
     }
 
@@ -172,11 +180,7 @@
      *            RMIJRMPServerImpl has not been exported yet.
      */
     public Remote toStub() throws IOException {
-        if (exportedWrapper != null) {
-            return RemoteObject.toStub(exportedWrapper);
-        } else {
-            return RemoteObject.toStub(this);
-        }
+        return RemoteObject.toStub(this);
     }
 
     /**
@@ -206,7 +210,7 @@
         RMIConnection client =
             new RMIConnectionImpl(this, connectionId, getDefaultClassLoader(),
                                   subject, env);
-        export(client);
+        export(client, jmxRmiFilter);
         return client;
     }
 
@@ -223,56 +227,38 @@
      * server failed.
      */
     protected void closeServer() throws IOException {
-        if (exportedWrapper != null) {
-            unexport(exportedWrapper, true);
-        } else {
-            unexport(this, true);
-        }
+        unexport(this, true);
     }
 
+    /**
+     * Check that a type in the remote invocation of {@link RMIServerImpl#newClient}
+     * is one of the {@code allowedTypes}.
+     *
+     * @param clazz       the class; may be null
+     * @param size        the size for arrays, otherwise is 0
+     * @param nObjectRefs the current number of object references
+     * @param depth       the current depth
+     * @param streamBytes the current number of bytes consumed
+     * @return {@code ObjectInputFilter.Status.ALLOWED} if the class is allowed,
+     *          otherwise {@code ObjectInputFilter.Status.REJECTED}
+     */
+    ObjectInputFilter.Status newClientCheckInput(ObjectInputFilter.FilterInfo filterInfo) {
+        ObjectInputFilter.Status status = ObjectInputFilter.Status.UNDECIDED;
+        if (allowedTypes != null && filterInfo.serialClass() != null) {
+            // If enabled, check type
+            String type = filterInfo.serialClass().getName();
+            if (allowedTypes.contains(type))
+                status = ObjectInputFilter.Status.ALLOWED;
+            else
+                status = ObjectInputFilter.Status.REJECTED;
+        }
+        return status;
+    }
     private final int port;
     private final RMIClientSocketFactory csf;
     private final RMIServerSocketFactory ssf;
     private final Map<String, ?> env;
-
-    private static class ExportedWrapper implements RMIServer, DeserializationChecker {
-        private final RMIServer impl;
-        private final List<String> allowedTypes;
-        private ExportedWrapper(RMIServer impl, List<String> credentialsTypes) {
-            this.impl = impl;
-            allowedTypes = credentialsTypes;
-        }
-
-        @Override
-        public String getVersion() throws RemoteException {
-            return impl.getVersion();
-        }
-
-        @Override
-        public RMIConnection newClient(Object credentials) throws IOException {
-            return impl.newClient(credentials);
-        }
-
-        @Override
-        public void check(Method method, ObjectStreamClass descriptor,
-                int paramIndex, int callID) {
-
-            String type = descriptor.getName();
-            if (!allowedTypes.contains(type)) {
-                throw new ClassCastException("Unsupported type: " + type);
-            }
-        }
-
-        @Override
-        public void checkProxyClass(Method method, String[] ifaces,
-                int paramIndex, int callID) {
-            if (ifaces != null && ifaces.length > 0) {
-                for (String iface : ifaces) {
-                    if (!allowedTypes.contains(iface)) {
-                        throw new ClassCastException("Unsupported type: " + iface);
-                    }
-                }
-            }
-        }
-    }
+    private final Set<String> allowedTypes;
+    private final ObjectInputFilter jmxRmiFilter;
+    private final ObjectInputFilter cFilter;
 }
--- a/src/share/classes/javax/naming/directory/BasicAttributes.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/javax/naming/directory/BasicAttributes.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2017, 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
@@ -302,8 +302,8 @@
         s.defaultReadObject();  // read in the ignoreCase flag
         int n = s.readInt();    // number of attributes
         attrs = (n >= 1)
-            ? new Hashtable<String,Attribute>(n * 2)
-            : new Hashtable<String,Attribute>(2); // can't have initial size of 0 (grrr...)
+                ? new Hashtable<>(1 + (int) (Math.min(768, n) / .75f))
+                : new Hashtable<>(2); // can't have initial size of 0 (grrr...)
         while (--n >= 0) {
             put((Attribute)s.readObject());
         }
--- a/src/share/classes/javax/swing/UIDefaults.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/javax/swing/UIDefaults.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, 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
@@ -305,7 +305,8 @@
                     if (c != null) {
                         b = ResourceBundle.getBundle(bundleName, l, c);
                     } else {
-                        b = ResourceBundle.getBundle(bundleName, l);
+                        b = ResourceBundle.getBundle(bundleName, l,
+                                ClassLoader.getSystemClassLoader());
                     }
                     Enumeration keys = b.getKeys();
 
--- a/src/share/classes/javax/swing/text/DefaultEditorKit.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/javax/swing/text/DefaultEditorKit.java	Tue Jan 16 22:58:44 2018 -0800
@@ -109,7 +109,7 @@
      * @return the command list
      */
     public Action[] getActions() {
-        return defaultActions;
+        return defaultActions.clone();
     }
 
     /**
--- a/src/share/classes/javax/swing/text/html/CSS.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/javax/swing/text/html/CSS.java	Tue Jan 16 22:58:44 2018 -0800
@@ -3352,7 +3352,7 @@
         s.defaultReadObject();
         // Reconstruct the hashtable.
         int numValues = s.readInt();
-        valueConvertor = new Hashtable<Object, Object>(Math.max(1, numValues));
+        valueConvertor = new Hashtable<Object, Object>();
         while (numValues-- > 0) {
             Object key = s.readObject();
             Object value = s.readObject();
--- a/src/share/classes/sun/awt/resources/awt_de.properties	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/awt/resources/awt_de.properties	Tue Jan 16 22:58:44 2018 -0800
@@ -44,7 +44,7 @@
 AWT.subtract=NumPad -
 AWT.decimal=NumPad .
 AWT.divide=NumPad /
-AWT.delete=L\u00F6schen
+AWT.delete=Entf
 AWT.numLock=Num
 AWT.scrollLock=Rollen
 AWT.f1=F1
--- a/src/share/classes/sun/launcher/resources/launcher_es.properties	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/launcher/resources/launcher_es.properties	Tue Jan 16 22:58:44 2018 -0800
@@ -28,13 +28,13 @@
 
 java.launcher.opt.datamodel  =\    -d{0}\t  usar un modelo de datos de {0} bits, si est\u00E1 disponible\n
 java.launcher.opt.vmselect   =\    {0}\t  para seleccionar la VM "{1}"\n
-java.launcher.opt.hotspot    =\    {0}\t  es un sin\u00F3nimo de la VM "{1}" [anticuada]\n
+java.launcher.opt.hotspot    =\    {0}\t  es un sin\u00F3nimo de la VM "{1}" [en desuso]\n
 
 java.launcher.ergo.message1  =\                  La VM por defecto es {0}
 java.launcher.ergo.message2  =\                  porque la ejecuci\u00F3n se est\u00E1 llevando a cabo en una m\u00E1quina de clase de servidor.\n
 
 # Translators please note do not translate the options themselves
-java.launcher.opt.footer     =\    -cp <ruta de acceso de b\u00FAsqueda de clases de los directorios y los archivos zip/jar>\n    -classpath <ruta de acceso de b\u00FAsqueda de clases de los directorios y los archivos zip/jar>\n                  Lista separada por {0} de directorios, archivos JAR\n                  y archivos ZIP para buscar archivos de clase.\n    -D<nombre>=<valor>\n                  definir una propiedad del sistema\n    -verbose:[class|gc|jni]\n                  activar la salida verbose\n    -version      imprimir la versi\u00F3n del producto y salir\n    -version:<valor>\n                  Advertencia: Esta funci\u00F3n est\u00E1 anticuada y se eliminar\u00E1\n                  en una versi\u00F3n futura.\n                  es necesario que se ejecute la versi\u00F3n especificada\n    -showversion  imprimir la versi\u00F3n del producto y continuar\n    -jre-restrict-search | -no-jre-restrict-search\n                  Advertencia: Esta funci\u00F3n est\u00E1 anticuada y se eliminar\u00E1\n                  en una versi\u00F3n futura.\n                  incluir/excluir JRE privados de usuario en la b\u00FAsqueda de versi\u00F3n\n    -? -help      imprimir este mensaje de ayuda\n    -X            imprimir la ayuda sobre las opciones que no sean est\u00E1ndar\n    -ea[:<nombre paquete>...|:<nombre clase>]\n    -enableassertions[:<nombre paquete>...|:<nombre clase>]\n                  activar afirmaciones con la granularidad especificada\n    -da[:<nombre paquete>...|:<nombre clase>]\n    -disableassertions[:<nombre paquete>...|:<nombre clase>]\n                  desactivar afirmaciones con la granularidad especificada\n    -esa | -enablesystemassertions\n                  activar afirmaciones del sistema\n    -dsa | -disablesystemassertions\n                  desactivar afirmaciones del sistema\n    -agentlib:<nombre bib>[=<opciones>]\n                  cargar la biblioteca de agente nativa <nombre bib>, como -agentlib:hprof\n                  v\u00E9ase tambi\u00E9n -agentlib:jdwp=help y -agentlib:hprof=help\n    -agentpath:<nombre ruta acceso>[=<opciones>]\n                  cargar biblioteca de agente nativa con el nombre de la ruta de acceso completa\n    -javaagent:<ruta acceso jar>[=<opciones>]\n                  cargar agente de lenguaje de programaci\u00F3n Java, v\u00E9ase java.lang.instrument\n    -splash:<ruta acceso imagen>\n                  mostrar una pantalla de presentaci\u00F3n con la imagen especificada\nConsulte http://www.oracle.com/technetwork/java/javase/documentation/index.html para obtener m\u00E1s informaci\u00F3n.
+java.launcher.opt.footer     =\    -cp <ruta de acceso de b\u00FAsqueda de clases de los directorios y los archivos zip/jar>\n    -classpath <ruta de acceso de b\u00FAsqueda de clases de los directorios y los archivos zip/jar>\n                  Lista separada por {0} de directorios, archivos JAR\n                  y archivos ZIP para buscar archivos de clase.\n    -D<nombre>=<valor>\n                  definir una propiedad del sistema\n    -verbose:[class|gc|jni]\n                  activar la salida verbose\n    -version      imprimir la versi\u00F3n del producto y salir\n    -version:<valor>\n                  Advertencia: Esta funci\u00F3n est\u00E1 en desuso y se eliminar\u00E1\n                  en una versi\u00F3n futura.\n                  es necesario que se ejecute la versi\u00F3n especificada\n    -showversion  imprimir la versi\u00F3n del producto y continuar\n    -jre-restrict-search | -no-jre-restrict-search\n                  Advertencia: Esta funci\u00F3n est\u00E1 en desuso y se eliminar\u00E1\n                  en una versi\u00F3n futura.\n                  incluir/excluir JRE privados de usuario en la b\u00FAsqueda de versi\u00F3n\n    -? -help      imprimir este mensaje de ayuda\n    -X            imprimir la ayuda sobre las opciones que no sean est\u00E1ndar\n    -ea[:<nombre paquete>...|:<nombre clase>]\n    -enableassertions[:<nombre paquete>...|:<nombre clase>]\n                  activar afirmaciones con la granularidad especificada\n    -da[:<nombre paquete>...|:<nombre clase>]\n    -disableassertions[:<nombre paquete>...|:<nombre clase>]\n                  desactivar afirmaciones con la granularidad especificada\n    -esa | -enablesystemassertions\n                  activar afirmaciones del sistema\n    -dsa | -disablesystemassertions\n                  desactivar afirmaciones del sistema\n    -agentlib:<nombre bib>[=<opciones>]\n                  cargar la biblioteca de agente nativa <nombre bib>, como -agentlib:hprof\n                  v\u00E9ase tambi\u00E9n -agentlib:jdwp=help y -agentlib:hprof=help\n    -agentpath:<nombre ruta acceso>[=<opciones>]\n                  cargar biblioteca de agente nativa con el nombre de la ruta de acceso completa\n    -javaagent:<ruta acceso jar>[=<opciones>]\n                  cargar agente de lenguaje de programaci\u00F3n Java, v\u00E9ase java.lang.instrument\n    -splash:<ruta acceso imagen>\n                  mostrar una pantalla de presentaci\u00F3n con la imagen especificada\nConsulte http://www.oracle.com/technetwork/java/javase/documentation/index.html para obtener m\u00E1s informaci\u00F3n.
 
 # Translators please note do not translate the options themselves
 java.launcher.X.usage=\    -Xmixed           ejecuci\u00F3n de modo mixto (por defecto)\n    -Xint             s\u00F3lo ejecuci\u00F3n de modo interpretado\n    -Xbootclasspath:<directorios y archivos zip/jar separados por {0}>\n                      definir la ruta de acceso de b\u00FAsqueda para los recursos y clases de inicializaci\u00F3n de datos\n    -Xbootclasspath/a:<directorios y archivos zip/jar separados por {0}>\n                      agregar al final de la ruta de acceso de la clase de inicializaci\u00F3n de datos\n    -Xbootclasspath/p:<directorios y archivos zip/jar separados por {0}>\n                      anteponer a la ruta de acceso de la clase de inicializaci\u00F3n de datos\n    -Xdiag            mostrar mensajes de diagn\u00F3stico adicionales\n    -Xnoclassgc       desactivar la recolecci\u00F3n de basura de clases\n    -Xincgc           activar la recolecci\u00F3n de basura de clases\n    -Xloggc:<archivo> registrar el estado de GC en un archivo con registros de hora\n    -Xbatch           desactivar compilaci\u00F3n en segundo plano\n    -Xms<tama\u00F1o>      definir tama\u00F1o de pila Java inicial\n    -Xmx<tama\u00F1o>      definir tama\u00F1o de pila Java m\u00E1ximo\n    -Xss<tama\u00F1o>      definir tama\u00F1o de la pila del thread de Java\n    -Xprof            datos de salida de creaci\u00F3n de perfil de CPU\n    -Xfuture          activar las comprobaciones m\u00E1s estrictas, anticip\u00E1ndose al futuro valor por defecto\n    -Xrs              reducir el uso de se\u00F1ales de sistema operativo por parte de Java/VM (consulte la documentaci\u00F3n)\n    -Xcheck:jni       realizar comprobaciones adicionales para las funciones de JNI\n    -Xshare:off       no intentar usar datos de clase compartidos\n    -Xshare:auto      usar datos de clase compartidos si es posible (valor por defecto)\n    -Xshare:on        es obligatorio el uso de datos de clase compartidos, de lo contrario se emitir\u00E1 un fallo.\n    -XshowSettings    mostrar todos los valores y continuar\n    -XshowSettings:all\n                      mostrar todos los valores y continuar\n    -XshowSettings:vm mostrar todos los valores de la VM y continuar\n    -XshowSettings:properties\n                      mostrar todos los valores de las propiedades y continuar\n    -XshowSettings:locale\n                      mostrar todos los valores relacionados con la configuraci\u00F3n regional y continuar\n\nLas opciones -X no son est\u00E1ndar, por lo que podr\u00EDan cambiarse sin previo aviso.\n
--- a/src/share/classes/sun/launcher/resources/launcher_ko.properties	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/launcher/resources/launcher_ko.properties	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2007, 2017, 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
@@ -47,7 +47,7 @@
 java.launcher.cls.error2=\uC624\uB958: {1} \uD074\uB798\uC2A4\uC5D0\uC11C \uAE30\uBCF8 \uBA54\uC18C\uB4DC\uAC00 {0}\uC774(\uAC00) \uC544\uB2D9\uB2C8\uB2E4. \uB2E4\uC74C \uD615\uC2DD\uC73C\uB85C \uAE30\uBCF8 \uBA54\uC18C\uB4DC\uB97C \uC815\uC758\uD558\uC2ED\uC2DC\uC624.\n   public static void main(String[] args)
 java.launcher.cls.error3=\uC624\uB958: \uAE30\uBCF8 \uBA54\uC18C\uB4DC\uB294 {0} \uD074\uB798\uC2A4\uC5D0\uC11C void \uC720\uD615\uC758 \uAC12\uC744 \uBC18\uD658\uD574\uC57C \uD569\uB2C8\uB2E4. \n\uB2E4\uC74C \uD615\uC2DD\uC73C\uB85C \uAE30\uBCF8 \uBA54\uC18C\uB4DC\uB97C \uC815\uC758\uD558\uC2ED\uC2DC\uC624.\n   public static void main(String[] args)
 java.launcher.cls.error4=\uC624\uB958: {0} \uD074\uB798\uC2A4\uC5D0\uC11C \uAE30\uBCF8 \uBA54\uC18C\uB4DC\uB97C \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4. \uB2E4\uC74C \uD615\uC2DD\uC73C\uB85C \uAE30\uBCF8 \uBA54\uC18C\uB4DC\uB97C \uC815\uC758\uD558\uC2ED\uC2DC\uC624.\r\n   public static void main(String[] args)\r\n\uB610\uB294 JavaFX \uC560\uD50C\uB9AC\uCF00\uC774\uC158 \uD074\uB798\uC2A4\uB294 {1}\uC744(\uB97C) \uD655\uC7A5\uD574\uC57C \uD569\uB2C8\uB2E4.
-java.launcher.cls.error5=\uC624\uB958: \uC774 \uC560\uD50C\uB9AC\uCF00\uC774\uC158\uC744 \uC2E4\uD589\uD558\uB294 \uB370 \uD544\uC694\uD55C JavaFX \uB7F0\uD0C0\uC784 \uAD6C\uC131 \uC694\uC18C\uAC00 \uB204\uB77D\uB418\uC5C8\uC2B5\uB2C8\uB2E4.
+java.launcher.cls.error5=\uC624\uB958: \uC774 \uC560\uD50C\uB9AC\uCF00\uC774\uC158\uC744 \uC2E4\uD589\uD558\uB294 \uB370 \uD544\uC694\uD55C JavaFX \uB7F0\uD0C0\uC784 \uAD6C\uC131\uC694\uC18C\uAC00 \uB204\uB77D\uB418\uC5C8\uC2B5\uB2C8\uB2E4.
 java.launcher.jar.error1=\uC624\uB958: {0} \uD30C\uC77C\uC744 \uC5F4\uB824\uACE0 \uC2DC\uB3C4\uD558\uB294 \uC911 \uC608\uC0C1\uCE58 \uC54A\uC740 \uC624\uB958\uAC00 \uBC1C\uC0DD\uD588\uC2B5\uB2C8\uB2E4.
 java.launcher.jar.error2={0}\uC5D0\uC11C Manifest\uB97C \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4.
 java.launcher.jar.error3={0}\uC5D0 \uAE30\uBCF8 Manifest \uC18D\uC131\uC774 \uC5C6\uC2B5\uB2C8\uB2E4.
--- a/src/share/classes/sun/management/jmxremote/ConnectorBootstrap.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/management/jmxremote/ConnectorBootstrap.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, 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
@@ -30,7 +30,7 @@
 import java.io.FileInputStream;
 import java.io.IOException;
 import java.io.InputStream;
-import java.io.Serializable;
+import sun.misc.ObjectInputFilter;
 import java.lang.management.ManagementFactory;
 import java.net.InetAddress;
 import java.net.MalformedURLException;
@@ -43,7 +43,6 @@
 import java.rmi.registry.Registry;
 import java.rmi.server.RMIClientSocketFactory;
 import java.rmi.server.RMIServerSocketFactory;
-import java.rmi.server.RMISocketFactory;
 import java.rmi.server.RemoteObject;
 import java.rmi.server.UnicastRemoteObject;
 import java.security.KeyStore;
@@ -83,6 +82,7 @@
 import sun.rmi.server.UnicastRef;
 import sun.rmi.server.UnicastServerRef;
 import sun.rmi.server.UnicastServerRef2;
+import sun.rmi.transport.LiveRef;
 
 /**
  * This class initializes and starts the RMIConnectorServer for JSR 163
@@ -141,6 +141,8 @@
                 "com.sun.management.jmxremote.ssl.need.client.auth";
         public static final String SSL_CONFIG_FILE_NAME =
                 "com.sun.management.jmxremote.ssl.config.file";
+        public static final String SERIAL_FILTER_PATTERN =
+                "com.sun.management.jmxremote.serial.filter.pattern";
     }
 
     /**
@@ -181,7 +183,8 @@
         public Remote exportObject(Remote obj,
                 int port,
                 RMIClientSocketFactory csf,
-                RMIServerSocketFactory ssf)
+                RMIServerSocketFactory ssf,
+                ObjectInputFilter filter)
                 throws RemoteException {
 
             synchronized (this) {
@@ -192,9 +195,9 @@
 
             final UnicastServerRef ref;
             if (csf == null && ssf == null) {
-                ref = new UnicastServerRef(port);
+                ref = new UnicastServerRef(new LiveRef(port), filter);
             } else {
-                ref = new UnicastServerRef2(port, csf, ssf);
+                ref = new UnicastServerRef2(port, csf, ssf, filter);
             }
             return ref.exportObject(obj, null, true);
         }
@@ -434,6 +437,7 @@
 
         final String bindAddress =
                 props.getProperty(PropertyNames.HOST);
+        final String jmxRmiFilter = props.getProperty(PropertyNames.SERIAL_FILTER_PATTERN);
 
         if (log.debugOn()) {
             log.debug("startRemoteConnectorServer",
@@ -470,7 +474,7 @@
                     sslConfigFileName, enabledCipherSuitesList,
                     enabledProtocolsList, sslNeedClientAuth,
                     useAuthentication, loginConfigName,
-                    passwordFileName, accessFileName, bindAddress);
+                    passwordFileName, accessFileName, bindAddress, jmxRmiFilter);
             cs = data.jmxConnectorServer;
             url = data.jmxRemoteURL;
             log.config("startRemoteConnectorServer",
@@ -510,9 +514,7 @@
         // This RMI server should not keep the VM alive
         Map<String, Object> env = new HashMap<>();
         env.put(RMIExporter.EXPORTER_ATTRIBUTE, new PermanentExporter());
-        env.put(EnvHelp.CREDENTIAL_TYPES, new String[]{
-            String[].class.getName(), String.class.getName()
-        });
+        env.put(EnvHelp.CREDENTIALS_FILTER_PATTERN, String.class.getName() + ";!*");
 
         // The local connector server need only be available via the
         // loopback connection.
@@ -728,7 +730,8 @@
             String loginConfigName,
             String passwordFileName,
             String accessFileName,
-            String bindAddress)
+            String bindAddress,
+            String jmxRmiFilter)
             throws IOException, MalformedURLException {
 
         /* Make sure we use non-guessable RMI object IDs.  Otherwise
@@ -743,9 +746,11 @@
         PermanentExporter exporter = new PermanentExporter();
 
         env.put(RMIExporter.EXPORTER_ATTRIBUTE, exporter);
-        env.put(EnvHelp.CREDENTIAL_TYPES, new String[]{
-            String[].class.getName(), String.class.getName()
-        });
+        env.put(EnvHelp.CREDENTIALS_FILTER_PATTERN, String.class.getName() + ";!*");
+
+        if(jmxRmiFilter != null && !jmxRmiFilter.isEmpty()) {
+            env.put(EnvHelp.SERIAL_FILTER_PATTERN, jmxRmiFilter);
+        }
 
         boolean useSocketFactory = bindAddress != null && !useSsl;
 
--- a/src/share/classes/sun/management/jmxremote/SingleEntryRegistry.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/management/jmxremote/SingleEntryRegistry.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, 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
@@ -46,7 +46,7 @@
 public class SingleEntryRegistry extends RegistryImpl {
     SingleEntryRegistry(int port, String name, Remote object)
             throws RemoteException {
-        super(port);
+        super(port, null, null, SingleEntryRegistry::singleRegistryFilter);
         this.name = name;
         this.object = object;
     }
--- a/src/share/classes/sun/management/resources/agent_de.properties	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/management/resources/agent_de.properties	Tue Jan 16 22:58:44 2018 -0800
@@ -1,6 +1,6 @@
 #
 #
-# Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2004, 2017, 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
@@ -43,7 +43,7 @@
 agent.err.premain.notfound         = premain(String) ist in Agent-Klasse nicht vorhanden
 agent.err.agentclass.access.denied = Zugriff auf premain(String) wurde abgelehnt
 agent.err.invalid.agentclass       = Ung\u00FCltiger Eigenschaftswert f\u00FCr com.sun.management.agent.class
-agent.err.invalid.state            = Ung\u00FCltiger Agent-Zustand
+agent.err.invalid.state            = Ung\u00FCltiger Agent-Zustand: {0}
 agent.err.invalid.jmxremote.port   = Ung\u00FCltige Nummer f\u00FCr com.sun.management.jmxremote.port
 agent.err.invalid.jmxremote.rmi.port = Ung\u00FCltige Nummer f\u00FCr com.sun.management.jmxremote.rmi.port
 
--- a/src/share/classes/sun/management/resources/agent_es.properties	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/management/resources/agent_es.properties	Tue Jan 16 22:58:44 2018 -0800
@@ -1,6 +1,6 @@
 #
 #
-# Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2004, 2017, 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
@@ -43,7 +43,7 @@
 agent.err.premain.notfound         = premain(String) no existe en la clase del agente
 agent.err.agentclass.access.denied = Acceso denegado a premain(String)
 agent.err.invalid.agentclass       = Valor de propiedad com.sun.management.agent.class no v\u00E1lido
-agent.err.invalid.state            = Estado del agente no v\u00E1lido
+agent.err.invalid.state            = Estado de agente no v\u00E1lido: {0}
 agent.err.invalid.jmxremote.port   = N\u00FAmero com.sun.management.jmxremote.port no v\u00E1lido
 agent.err.invalid.jmxremote.rmi.port = N\u00FAmero com.sun.management.jmxremote.rmi.port no v\u00E1lido
 
--- a/src/share/classes/sun/management/resources/agent_fr.properties	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/management/resources/agent_fr.properties	Tue Jan 16 22:58:44 2018 -0800
@@ -1,6 +1,6 @@
 #
 #
-# Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2004, 2017, 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
@@ -43,7 +43,7 @@
 agent.err.premain.notfound         = premain(String) n'existe pas dans la classe d'agents
 agent.err.agentclass.access.denied = Acc\u00E8s \u00E0 premain(String) refus\u00E9
 agent.err.invalid.agentclass       = Valeur de propri\u00E9t\u00E9 com.sun.management.agent.class incorrecte
-agent.err.invalid.state            = Etat de l'agent non valide
+agent.err.invalid.state            = Etat de l''agent non valide : {0}
 agent.err.invalid.jmxremote.port   = Num\u00E9ro com.sun.management.jmxremote.port incorrect
 agent.err.invalid.jmxremote.rmi.port = Num\u00E9ro com.sun.management.jmxremote.rmi.port non valide
 
--- a/src/share/classes/sun/management/resources/agent_it.properties	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/management/resources/agent_it.properties	Tue Jan 16 22:58:44 2018 -0800
@@ -1,6 +1,6 @@
 #
 #
-# Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2004, 2017, 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
@@ -43,7 +43,7 @@
 agent.err.premain.notfound         = premain(String) non esiste nella classe agente
 agent.err.agentclass.access.denied = Accesso negato a premain(String)
 agent.err.invalid.agentclass       = Valore propriet\u00E0 com.sun.management.agent.class non valido
-agent.err.invalid.state            = Stato agente non valido
+agent.err.invalid.state            = Stato agente non valido: {0}
 agent.err.invalid.jmxremote.port   = Numero com.sun.management.jmxremote.port non valido
 agent.err.invalid.jmxremote.rmi.port = Numero com.sun.management.jmxremote.rmi.port non valido
 
--- a/src/share/classes/sun/management/resources/agent_ja.properties	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/management/resources/agent_ja.properties	Tue Jan 16 22:58:44 2018 -0800
@@ -1,6 +1,6 @@
 #
 #
-# Copyright (c) 2004, 2014, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2004, 2017, 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
@@ -43,7 +43,7 @@
 agent.err.premain.notfound         = premain(String)\u304C\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u30FB\u30AF\u30E9\u30B9\u306B\u5B58\u5728\u3057\u307E\u305B\u3093
 agent.err.agentclass.access.denied = premain(String)\u3078\u306E\u30A2\u30AF\u30BB\u30B9\u304C\u62D2\u5426\u3055\u308C\u307E\u3057\u305F
 agent.err.invalid.agentclass       = com.sun.management.agent.class\u30D7\u30ED\u30D1\u30C6\u30A3\u306E\u5024\u304C\u7121\u52B9\u3067\u3059
-agent.err.invalid.state            = \u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u306E\u72B6\u614B\u304C\u7121\u52B9\u3067\u3059
+agent.err.invalid.state            = \u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u306E\u72B6\u614B\u304C\u7121\u52B9\u3067\u3059: {0}
 agent.err.invalid.jmxremote.port   = com.sun.management.jmxremote.port\u306E\u756A\u53F7\u304C\u7121\u52B9\u3067\u3059
 agent.err.invalid.jmxremote.rmi.port = com.sun.management.jmxremote.rmi.port\u306E\u756A\u53F7\u304C\u7121\u52B9\u3067\u3059
 
--- a/src/share/classes/sun/management/resources/agent_ko.properties	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/management/resources/agent_ko.properties	Tue Jan 16 22:58:44 2018 -0800
@@ -1,6 +1,6 @@
 #
 #
-# Copyright (c) 2004, 2016, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2004, 2017, 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
@@ -43,7 +43,7 @@
 agent.err.premain.notfound         = \uC5D0\uC774\uC804\uD2B8 \uD074\uB798\uC2A4\uC5D0 premain(\uBB38\uC790\uC5F4)\uC774 \uC874\uC7AC\uD558\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.
 agent.err.agentclass.access.denied = premain(\uBB38\uC790\uC5F4)\uC5D0 \uB300\uD55C \uC561\uC138\uC2A4\uAC00 \uAC70\uBD80\uB418\uC5C8\uC2B5\uB2C8\uB2E4.
 agent.err.invalid.agentclass       = com.sun.management.agent.class \uC18D\uC131 \uAC12\uC774 \uBD80\uC801\uD569\uD569\uB2C8\uB2E4.
-agent.err.invalid.state            = \uBD80\uC801\uD569\uD55C \uC5D0\uC774\uC804\uD2B8 \uC0C1\uD0DC
+agent.err.invalid.state            = \uBD80\uC801\uD569\uD55C \uC5D0\uC774\uC804\uD2B8 \uC0C1\uD0DC: {0}
 agent.err.invalid.jmxremote.port   = com.sun.management.jmxremote.port \uBC88\uD638\uAC00 \uBD80\uC801\uD569\uD569\uB2C8\uB2E4.
 agent.err.invalid.jmxremote.rmi.port = \uBD80\uC801\uD569\uD55C com.sun.management.jmxremote.rmi.port \uBC88\uD638
 
--- a/src/share/classes/sun/management/resources/agent_pt_BR.properties	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/management/resources/agent_pt_BR.properties	Tue Jan 16 22:58:44 2018 -0800
@@ -1,6 +1,6 @@
 #
 #
-# Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2004, 2017, 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
@@ -43,7 +43,7 @@
 agent.err.premain.notfound         = premain(String) n\u00E3o existe na classe do agente
 agent.err.agentclass.access.denied = Acesso negado a premain(String)
 agent.err.invalid.agentclass       = Valor inv\u00E1lido da propriedade com.sun.management.agent.class
-agent.err.invalid.state            = Estado de agente inv\u00E1lido
+agent.err.invalid.state            = Estado inv\u00E1lido do agente: {0}
 agent.err.invalid.jmxremote.port   = N\u00FAmero inv\u00E1lido de com.sun.management.jmxremote.port
 agent.err.invalid.jmxremote.rmi.port = N\u00FAmero inv\u00E1lido do com.sun.management.jmxremote.rmi.port
 
--- a/src/share/classes/sun/management/resources/agent_sv.properties	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/management/resources/agent_sv.properties	Tue Jan 16 22:58:44 2018 -0800
@@ -43,7 +43,7 @@
 agent.err.premain.notfound         = premain(String) finns inte i agentklassen
 agent.err.agentclass.access.denied = \u00C5tkomst till premain(String) nekad
 agent.err.invalid.agentclass       = Ogiltigt egenskapsv\u00E4rde f\u00F6r com.sun.management.agent.class
-agent.err.invalid.state            = Ogiltigt agenttillst\u00E5nd
+agent.err.invalid.state            = Ogiltig agentstatus: {0}
 agent.err.invalid.jmxremote.port   = Ogiltigt com.sun.management.jmxremote.port-nummer
 agent.err.invalid.jmxremote.rmi.port = Ogiltigt com.sun.management.jmxremote.rmi.port-nummer
 
--- a/src/share/classes/sun/management/resources/agent_zh_CN.properties	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/management/resources/agent_zh_CN.properties	Tue Jan 16 22:58:44 2018 -0800
@@ -1,6 +1,6 @@
 #
 #
-# Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2004, 2017, 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
@@ -43,7 +43,7 @@
 agent.err.premain.notfound         = \u4EE3\u7406\u7C7B\u4E2D\u4E0D\u5B58\u5728 premain(String)
 agent.err.agentclass.access.denied = \u62D2\u7EDD\u8BBF\u95EE premain(String)
 agent.err.invalid.agentclass       = com.sun.management.agent.class \u5C5E\u6027\u503C\u65E0\u6548
-agent.err.invalid.state            = \u4EE3\u7406\u72B6\u6001\u65E0\u6548
+agent.err.invalid.state            = \u65E0\u6548\u7684\u4EE3\u7406\u72B6\u6001: {0}
 agent.err.invalid.jmxremote.port   = com.sun.management.jmxremote.port \u7F16\u53F7\u65E0\u6548
 agent.err.invalid.jmxremote.rmi.port = com.sun.management.jmxremote.rmi.port \u7F16\u53F7\u65E0\u6548
 
--- a/src/share/classes/sun/management/resources/agent_zh_TW.properties	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/management/resources/agent_zh_TW.properties	Tue Jan 16 22:58:44 2018 -0800
@@ -1,6 +1,6 @@
 #
 #
-# Copyright (c) 2004, 2016, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2004, 2017, 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
@@ -43,7 +43,7 @@
 agent.err.premain.notfound         = \u4EE3\u7406\u7A0B\u5F0F\u985E\u5225\u4E2D\u4E0D\u5B58\u5728 premain(String)
 agent.err.agentclass.access.denied = \u5B58\u53D6 premain(String) \u906D\u5230\u62D2\u7D55
 agent.err.invalid.agentclass       = com.sun.management.agent.class \u5C6C\u6027\u503C\u7121\u6548
-agent.err.invalid.state            = \u7121\u6548\u7684\u4EE3\u7406\u7A0B\u5F0F\u72C0\u614B
+agent.err.invalid.state            = \u7121\u6548\u7684\u4EE3\u7406\u7A0B\u5F0F\u72C0\u614B: {0}
 agent.err.invalid.jmxremote.port   = com.sun.management.jmxremote.port \u865F\u78BC\u7121\u6548
 agent.err.invalid.jmxremote.rmi.port = com.sun.management.jmxremote.rmi.port \u865F\u78BC\u7121\u6548
 
--- a/src/share/classes/sun/misc/JavaObjectInputStreamAccess.java	Mon Jan 08 22:36:23 2018 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,41 +0,0 @@
-/*
- * Copyright (c) 2016, 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.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * 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.
- */
-
-package sun.misc;
-
-import java.io.ObjectInputStream;
-
-/**
- * The interface to specify methods for accessing {@code ObjectInputStream}
- * @author sjiang
- */
-public interface JavaObjectInputStreamAccess {
-    /**
-     * Sets a descriptor validating.
-     * @param ois stream to have the descriptors validated
-     * @param validator validator used to validate a descriptor.
-     */
-    public void setValidator(ObjectInputStream ois, ObjectStreamClassValidator validator);
-}
--- a/src/share/classes/sun/misc/ObjectStreamClassValidator.java	Mon Jan 08 22:36:23 2018 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,43 +0,0 @@
-/*
- * Copyright (c) 2016, 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.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * 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.
- */
-
-package sun.misc;
-
-import java.io.ObjectStreamClass;
-
-/**
- * A callback used by {@code ObjectInputStream} to do descriptor validation.
- *
- * @author sjiang
- */
-public interface ObjectStreamClassValidator {
-    /**
-     * This method will be called by ObjectInputStream to
-     * check a descriptor just before creating an object described by this descriptor.
-     * The object will not be created if this method throws a {@code RuntimeException}.
-     * @param descriptor descriptor to be checked.
-     */
-    public void validateDescriptor(ObjectStreamClass descriptor);
-}
--- a/src/share/classes/sun/misc/SharedSecrets.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/misc/SharedSecrets.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2017, 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
@@ -58,7 +58,6 @@
     private static JavaUtilZipFileAccess javaUtilZipFileAccess;
     private static JavaAWTAccess javaAWTAccess;
     private static JavaOISAccess javaOISAccess;
-    private static JavaObjectInputStreamAccess javaObjectInputStreamAccess;
 
     public static JavaUtilJarAccess javaUtilJarAccess() {
         if (javaUtilJarAccess == null) {
@@ -200,15 +199,4 @@
         }
         return javaAWTAccess;
     }
-
-    public static JavaObjectInputStreamAccess getJavaObjectInputStreamAccess() {
-        if (javaObjectInputStreamAccess == null) {
-            unsafe.ensureClassInitialized(ObjectInputStream.class);
-        }
-        return javaObjectInputStreamAccess;
-    }
-
-    public static void setJavaObjectInputStreamAccess(JavaObjectInputStreamAccess access) {
-        javaObjectInputStreamAccess = access;
-    }
 }
--- a/src/share/classes/sun/net/www/protocol/http/spnego/NegotiateCallbackHandler.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/net/www/protocol/http/spnego/NegotiateCallbackHandler.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2017, 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
@@ -35,6 +35,7 @@
 import javax.security.auth.callback.PasswordCallback;
 import javax.security.auth.callback.UnsupportedCallbackException;
 import sun.net.www.protocol.http.HttpCallerInfo;
+import sun.security.jgss.LoginConfigImpl;
 
 /**
  * @since 1.6
@@ -61,18 +62,21 @@
     private void getAnswer() {
         if (!answered) {
             answered = true;
-            PasswordAuthentication passAuth =
-                    Authenticator.requestPasswordAuthentication(
-                    hci.host, hci.addr, hci.port, hci.protocol,
-                    hci.prompt, hci.scheme, hci.url, hci.authType);
-            /**
-             * To be compatible with existing callback handler implementations,
-             * when the underlying Authenticator is canceled, username and
-             * password are assigned null. No exception is thrown.
-             */
-            if (passAuth != null) {
-                username = passAuth.getUserName();
-                password = passAuth.getPassword();
+
+            if (LoginConfigImpl.HTTP_USE_GLOBAL_CREDS) {
+                PasswordAuthentication passAuth =
+                        Authenticator.requestPasswordAuthentication(
+                                hci.host, hci.addr, hci.port, hci.protocol,
+                                hci.prompt, hci.scheme, hci.url, hci.authType);
+                /**
+                 * To be compatible with existing callback handler implementations,
+                 * when the underlying Authenticator is canceled, username and
+                 * password are assigned null. No exception is thrown.
+                 */
+                if (passAuth != null) {
+                    username = passAuth.getUserName();
+                    password = passAuth.getPassword();
+                }
             }
         }
     }
--- a/src/share/classes/sun/rmi/registry/RegistryImpl.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/rmi/registry/RegistryImpl.java	Tue Jan 16 22:58:44 2018 -0800
@@ -170,7 +170,7 @@
             }
         } else {
             LiveRef lref = new LiveRef(id, port, csf, ssf);
-            setup(new UnicastServerRef2(lref, RegistryImpl::registryFilter));
+            setup(new UnicastServerRef2(lref, serialFilter));
         }
     }
 
--- a/src/share/classes/sun/rmi/server/MarshalInputStream.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/rmi/server/MarshalInputStream.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2017, 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
@@ -34,8 +34,6 @@
 import java.security.AccessControlException;
 import java.security.Permission;
 import java.rmi.server.RMIClassLoader;
-import sun.misc.ObjectStreamClassValidator;
-import sun.misc.SharedSecrets;
 
 /**
  * MarshalInputStream is an extension of ObjectInputStream.  When resolving
@@ -53,11 +51,6 @@
  * @author      Peter Jones
  */
 public class MarshalInputStream extends ObjectInputStream {
-    interface StreamChecker extends ObjectStreamClassValidator {
-        void checkProxyInterfaceNames(String[] ifaces);
-    }
-
-    private volatile StreamChecker streamChecker = null;
 
     /**
      * Value of "java.rmi.server.useCodebaseOnly" property,
@@ -244,11 +237,6 @@
     protected Class<?> resolveProxyClass(String[] interfaces)
         throws IOException, ClassNotFoundException
     {
-        StreamChecker checker = streamChecker;
-        if (checker != null) {
-            checker.checkProxyInterfaceNames(interfaces);
-        }
-
         /*
          * Always read annotation written by MarshalOutputStream.
          */
@@ -328,28 +316,4 @@
     void useCodebaseOnly() {
         useCodebaseOnly = true;
     }
-
-    synchronized void setStreamChecker(StreamChecker checker) {
-        streamChecker = checker;
-        SharedSecrets.getJavaObjectInputStreamAccess().setValidator(this, checker);
-    }
-    @Override
-    protected ObjectStreamClass readClassDescriptor() throws IOException,
-            ClassNotFoundException {
-        ObjectStreamClass descriptor = super.readClassDescriptor();
-
-        validateDesc(descriptor);
-
-        return descriptor;
-    }
-
-    private void validateDesc(ObjectStreamClass descriptor) {
-        StreamChecker checker;
-        synchronized (this) {
-            checker = streamChecker;
-        }
-        if (checker != null) {
-            checker.validateDescriptor(descriptor);
-        }
-    }
 }
--- a/src/share/classes/sun/rmi/server/UnicastServerRef.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/rmi/server/UnicastServerRef.java	Tue Jan 16 22:58:44 2018 -0800
@@ -29,7 +29,6 @@
 import java.io.ObjectInput;
 import java.io.ObjectInputStream;
 import java.io.ObjectOutput;
-import java.io.ObjectStreamClass;
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
 import java.rmi.AccessException;
@@ -332,11 +331,16 @@
             logCall(obj, method);
 
             // unmarshal parameters
-            Object[] params = null;
+            Class<?>[] types = method.getParameterTypes();
+            Object[] params = new Object[types.length];
 
             try {
                 unmarshalCustomCallData(in);
-                params = unmarshalParameters(obj, method, marshalStream);
+                // Unmarshal the parameters
+                for (int i = 0; i < types.length; i++) {
+                    params[i] = unmarshalValue(types[i], in);
+                }
+
             } catch (AccessException aex) {
                 // For compatibility, AccessException is not wrapped in UnmarshalException
                 // disable saving any refs in the inputStream for GC
@@ -605,84 +609,4 @@
         }
     }
 
-    /**
-     * Unmarshal parameters for the given method of the given instance over
-     * the given marshalinputstream. Perform any necessary checks.
-     */
-    private Object[] unmarshalParameters(Object obj, Method method, MarshalInputStream in)
-    throws IOException, ClassNotFoundException {
-        return (obj instanceof DeserializationChecker) ?
-            unmarshalParametersChecked((DeserializationChecker)obj, method, in) :
-            unmarshalParametersUnchecked(method, in);
-    }
-
-    /**
-     * Unmarshal parameters for the given method of the given instance over
-     * the given marshalinputstream. Do not perform any additional checks.
-     */
-    private Object[] unmarshalParametersUnchecked(Method method, ObjectInput in)
-    throws IOException, ClassNotFoundException {
-        Class<?>[] types = method.getParameterTypes();
-        Object[] params = new Object[types.length];
-        for (int i = 0; i < types.length; i++) {
-            params[i] = unmarshalValue(types[i], in);
-        }
-        return params;
-    }
-
-    /**
-     * Unmarshal parameters for the given method of the given instance over
-     * the given marshalinputstream. Do perform all additional checks.
-     */
-    private Object[] unmarshalParametersChecked(
-        DeserializationChecker checker,
-        Method method, MarshalInputStream in)
-    throws IOException, ClassNotFoundException {
-        int callID = methodCallIDCount.getAndIncrement();
-        MyChecker myChecker = new MyChecker(checker, method, callID);
-        in.setStreamChecker(myChecker);
-        try {
-            Class<?>[] types = method.getParameterTypes();
-            Object[] values = new Object[types.length];
-            for (int i = 0; i < types.length; i++) {
-                myChecker.setIndex(i);
-                values[i] = unmarshalValue(types[i], in);
-            }
-            myChecker.end(callID);
-            return values;
-        } finally {
-            in.setStreamChecker(null);
-        }
-    }
-
-    private static class MyChecker implements MarshalInputStream.StreamChecker {
-        private final DeserializationChecker descriptorCheck;
-        private final Method method;
-        private final int callID;
-        private int parameterIndex;
-
-        MyChecker(DeserializationChecker descriptorCheck, Method method, int callID) {
-            this.descriptorCheck = descriptorCheck;
-            this.method = method;
-            this.callID = callID;
-        }
-
-        @Override
-        public void validateDescriptor(ObjectStreamClass descriptor) {
-            descriptorCheck.check(method, descriptor, parameterIndex, callID);
-        }
-
-        @Override
-        public void checkProxyInterfaceNames(String[] ifaces) {
-            descriptorCheck.checkProxyClass(method, ifaces, parameterIndex, callID);
-        }
-
-        void setIndex(int parameterIndex) {
-            this.parameterIndex = parameterIndex;
-        }
-
-        void end(int callId) {
-            descriptorCheck.end(callId);
-        }
-    }
 }
--- a/src/share/classes/sun/security/internal/spec/TlsMasterSecretParameterSpec.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/security/internal/spec/TlsMasterSecretParameterSpec.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2017, 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
@@ -48,6 +48,7 @@
     private final SecretKey premasterSecret;
     private final int majorVersion, minorVersion;
     private final byte[] clientRandom, serverRandom;
+    private final byte[] extendedMasterSecretSessionHash;
     private final String prfHashAlg;
     private final int prfHashLength;
     private final int prfBlockSize;
@@ -80,6 +81,50 @@
             int majorVersion, int minorVersion,
             byte[] clientRandom, byte[] serverRandom,
             String prfHashAlg, int prfHashLength, int prfBlockSize) {
+        this(premasterSecret, majorVersion, minorVersion,
+                clientRandom, serverRandom,
+                new byte[0],
+                prfHashAlg, prfHashLength, prfBlockSize);
+    }
+
+    /**
+     * Constructs a new TlsMasterSecretParameterSpec.
+     *
+     * <p>The <code>getAlgorithm()</code> method of <code>premasterSecret</code>
+     * should return <code>"TlsRsaPremasterSecret"</code> if the key exchange
+     * algorithm was RSA and <code>"TlsPremasterSecret"</code> otherwise.
+     *
+     * @param premasterSecret the premaster secret
+     * @param majorVersion the major number of the protocol version
+     * @param minorVersion the minor number of the protocol version
+     * @param extendedMasterSecretSessionHash the session hash for
+     *        Extended Master Secret
+     * @param prfHashAlg the name of the TLS PRF hash algorithm to use.
+     *        Used only for TLS 1.2+.  TLS1.1 and earlier use a fixed PRF.
+     * @param prfHashLength the output length of the TLS PRF hash algorithm.
+     *        Used only for TLS 1.2+.
+     * @param prfBlockSize the input block size of the TLS PRF hash algorithm.
+     *        Used only for TLS 1.2+.
+     *
+     * @throws NullPointerException if premasterSecret is null
+     * @throws IllegalArgumentException if minorVersion or majorVersion are
+     *   negative or larger than 255
+     */
+    public TlsMasterSecretParameterSpec(SecretKey premasterSecret,
+            int majorVersion, int minorVersion,
+            byte[] extendedMasterSecretSessionHash,
+            String prfHashAlg, int prfHashLength, int prfBlockSize) {
+        this(premasterSecret, majorVersion, minorVersion,
+                new byte[0], new byte[0],
+                extendedMasterSecretSessionHash,
+                prfHashAlg, prfHashLength, prfBlockSize);
+    }
+
+    private TlsMasterSecretParameterSpec(SecretKey premasterSecret,
+            int majorVersion, int minorVersion,
+            byte[] clientRandom, byte[] serverRandom,
+            byte[] extendedMasterSecretSessionHash,
+            String prfHashAlg, int prfHashLength, int prfBlockSize) {
         if (premasterSecret == null) {
             throw new NullPointerException("premasterSecret must not be null");
         }
@@ -88,6 +133,9 @@
         this.minorVersion = checkVersion(minorVersion);
         this.clientRandom = clientRandom.clone();
         this.serverRandom = serverRandom.clone();
+        this.extendedMasterSecretSessionHash =
+                (extendedMasterSecretSessionHash != null ?
+                        extendedMasterSecretSessionHash.clone() : new byte[0]);
         this.prfHashAlg = prfHashAlg;
         this.prfHashLength = prfHashLength;
         this.prfBlockSize = prfBlockSize;
@@ -147,6 +195,17 @@
     }
 
     /**
+     * Returns a copy of the Extended Master Secret session hash.
+     *
+     * @return a copy of the Extended Master Secret session hash, or an empty
+     *         array if no extended master secret session hash was provided
+     *         at instantiation time
+     */
+    public byte[] getExtendedMasterSecretSessionHash() {
+        return extendedMasterSecretSessionHash.clone();
+    }
+
+    /**
      * Obtains the PRF hash algorithm to use in the PRF calculation.
      *
      * @return the hash algorithm.
--- a/src/share/classes/sun/security/jgss/GSSUtil.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/security/jgss/GSSUtil.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2017, 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
@@ -270,24 +270,17 @@
      */
     public static boolean useSubjectCredsOnly(GSSCaller caller) {
 
-        // HTTP/SPNEGO doesn't use the standard JAAS framework. Instead, it
-        // uses the java.net.Authenticator style, therefore always return
-        // false here.
+        String propValue = GetPropertyAction.privilegedGetProperty(
+                "javax.security.auth.useSubjectCredsOnly");
+
+        // Invalid values should be ignored and the default assumed.
         if (caller instanceof HttpCaller) {
-            return false;
+            // Default for HTTP/SPNEGO is false.
+            return "true".equalsIgnoreCase(propValue);
+        } else {
+            // Default for JGSS is true.
+            return !("false".equalsIgnoreCase(propValue));
         }
-        /*
-         * Don't use GetBooleanAction because the default value in the JRE
-         * (when this is unset) has to treated as true.
-         */
-        String propValue = AccessController.doPrivileged(
-                new GetPropertyAction("javax.security.auth.useSubjectCredsOnly",
-                "true"));
-        /*
-         * This property has to be explicitly set to "false". Invalid
-         * values should be ignored and the default "true" assumed.
-         */
-        return (!propValue.equalsIgnoreCase("false"));
     }
 
     /**
--- a/src/share/classes/sun/security/jgss/LoginConfigImpl.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/security/jgss/LoginConfigImpl.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2017, 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
@@ -29,6 +29,7 @@
 import javax.security.auth.login.AppConfigurationEntry;
 import javax.security.auth.login.Configuration;
 import org.ietf.jgss.Oid;
+import sun.security.action.GetPropertyAction;
 
 /**
  * A Configuration implementation especially designed for JGSS.
@@ -44,6 +45,16 @@
     private static final sun.security.util.Debug debug =
         sun.security.util.Debug.getInstance("gssloginconfig", "\t[GSS LoginConfigImpl]");
 
+    public static final boolean HTTP_USE_GLOBAL_CREDS;
+
+    static {
+        String prop = GetPropertyAction
+                .privilegedGetProperty("http.use.global.creds");
+        //HTTP_USE_GLOBAL_CREDS = "true".equalsIgnoreCase(prop); // default false
+        HTTP_USE_GLOBAL_CREDS = !"false".equalsIgnoreCase(prop); // default true
+    }
+
+
     /**
      * A new instance of LoginConfigImpl must be created for each login request
      * since it's only used by a single (caller, mech) pair
@@ -178,7 +189,11 @@
                 options.put("principal", "*");
                 options.put("isInitiator", "false");
             } else {
-                options.put("useTicketCache", "true");
+                if (caller instanceof HttpCaller && !HTTP_USE_GLOBAL_CREDS) {
+                    options.put("useTicketCache", "false");
+                } else {
+                    options.put("useTicketCache", "true");
+                }
                 options.put("doNotPrompt", "false");
             }
             return new AppConfigurationEntry[] {
--- a/src/share/classes/sun/security/pkcs11/P11KeyAgreement.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/security/pkcs11/P11KeyAgreement.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, 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
@@ -69,6 +69,17 @@
     // KeyAgreement from SunJCE as fallback for > 2 party agreement
     private KeyAgreement multiPartyAgreement;
 
+    private static class AllowKDF {
+
+        private static final boolean VALUE = getValue();
+
+        private static boolean getValue() {
+            return AccessController.doPrivileged(
+                (PrivilegedAction<Boolean>)
+                () -> Boolean.getBoolean("jdk.crypto.KeyAgreement.legacyKDF"));
+        }
+    }
+
     P11KeyAgreement(Token token, String algorithm, long mechanism) {
         super();
         this.token = token;
@@ -260,6 +271,7 @@
         if (algorithm == null) {
             throw new NoSuchAlgorithmException("Algorithm must not be null");
         }
+
         if (algorithm.equals("TlsPremasterSecret")) {
             // For now, only perform native derivation for TlsPremasterSecret
             // as that is required for FIPS compliance.
@@ -268,6 +280,14 @@
             // (bug not yet filed).
             return nativeGenerateSecret(algorithm);
         }
+
+        if (!algorithm.equalsIgnoreCase("TlsPremasterSecret") &&
+            !AllowKDF.VALUE) {
+
+            throw new NoSuchAlgorithmException("Unsupported secret key "
+                                               + "algorithm: " + algorithm);
+        }
+
         byte[] secret = engineGenerateSecret();
         // Maintain compatibility for SunJCE:
         // verify secret length is sensible for algorithm / truncate
--- a/src/share/classes/sun/security/pkcs11/P11KeyPairGenerator.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/security/pkcs11/P11KeyPairGenerator.java	Tue Jan 16 22:58:44 2018 -0800
@@ -141,6 +141,7 @@
     }
 
     // see JCA spec
+    @Override
     public void initialize(int keySize, SecureRandom random) {
         token.ensureValid();
         try {
@@ -162,6 +163,7 @@
     }
 
     // see JCA spec
+    @Override
     public void initialize(AlgorithmParameterSpec params, SecureRandom random)
             throws InvalidAlgorithmParameterException {
         token.ensureValid();
@@ -173,7 +175,7 @@
             }
             DHParameterSpec dhParams = (DHParameterSpec) params;
             tmpKeySize = dhParams.getP().bitLength();
-            checkKeySize(tmpKeySize, null);
+            checkKeySize(tmpKeySize, dhParams);
             // XXX sanity check params
         } else if (algorithm.equals("RSA")) {
             if (params instanceof RSAKeyGenParameterSpec == false) {
@@ -195,7 +197,7 @@
             }
             DSAParameterSpec dsaParams = (DSAParameterSpec) params;
             tmpKeySize = dsaParams.getP().bitLength();
-            checkKeySize(tmpKeySize, null);
+            checkKeySize(tmpKeySize, dsaParams);
             // XXX sanity check params
         } else if (algorithm.equals("EC")) {
             ECParameterSpec ecParams;
@@ -220,7 +222,7 @@
                     ("ECParameterSpec or ECGenParameterSpec required for EC");
             }
             tmpKeySize = ecParams.getCurve().getField().getFieldSize();
-            checkKeySize(tmpKeySize, null);
+            checkKeySize(tmpKeySize, ecParams);
         } else {
             throw new ProviderException("Unknown algorithm: " + algorithm);
         }
@@ -229,8 +231,7 @@
         this.random = random;
     }
 
-    // NOTE: 'params' is only used for checking RSA keys currently.
-    private void checkKeySize(int keySize, RSAKeyGenParameterSpec params)
+    private void checkKeySize(int keySize, AlgorithmParameterSpec params)
         throws InvalidAlgorithmParameterException {
         // check native range first
         if ((minKeySize != -1) && (keySize < minKeySize)) {
@@ -267,7 +268,8 @@
             if (algorithm.equals("RSA")) {
                 BigInteger tmpExponent = rsaPublicExponent;
                 if (params != null) {
-                    tmpExponent = params.getPublicExponent();
+                    tmpExponent =
+                        ((RSAKeyGenParameterSpec)params).getPublicExponent();
                 }
                 try {
                     // Reuse the checking in SunRsaSign provider.
@@ -277,10 +279,10 @@
                         minKeySize,
                         (maxKeySize==-1? Integer.MAX_VALUE:maxKeySize));
                 } catch (InvalidKeyException e) {
-                    throw new InvalidAlgorithmParameterException(e.getMessage());
+                    throw new InvalidAlgorithmParameterException(e);
                 }
-            } else {
-                if (algorithm.equals("DH") && (params != null)) {
+            } else if (algorithm.equals("DH")) {
+                if (params != null) {   // initialized with specified parameters
                     // sanity check, nobody really wants keys this large
                     if (keySize > 64 * 1024) {
                         throw new InvalidAlgorithmParameterException(
@@ -288,24 +290,44 @@
                             "The specific key size " +
                             keySize + " is not supported");
                     }
-                } else {
-                    // this restriction is in the spec for DSA
-                    // since we currently use DSA parameters for DH as well,
-                    // it also applies to DH if no parameters are specified
-                    if ((keySize != 2048) &&
-                        ((keySize > 1024) || ((keySize & 0x3f) != 0))) {
-                        throw new InvalidAlgorithmParameterException(algorithm +
-                            " key must be multiples of 64 if less than 1024 bits" +
-                            ", or 2048 bits. " +
+                } else {        // default parameters will be used.
+                    // Range is based on the values in
+                    // sun.security.provider.ParameterCache class.
+                    if ((keySize > 8192) || (keySize < 512) ||
+                            ((keySize & 0x3f) != 0)) {
+                        throw new InvalidAlgorithmParameterException(
+                            "DH key size must be multiple of 64, and can " +
+                            "only range from 512 to 8192 (inclusive). " +
                             "The specific key size " +
                             keySize + " is not supported");
                     }
+
+                    DHParameterSpec cache =
+                            ParameterCache.getCachedDHParameterSpec(keySize);
+                    // Except 2048 and 3072, not yet support generation of
+                    // parameters bigger than 1024 bits.
+                    if ((cache == null) && (keySize > 1024)) {
+                        throw new InvalidAlgorithmParameterException(
+                                "Unsupported " + keySize +
+                                "-bit DH parameter generation");
+                    }
+                }
+            } else {
+                // this restriction is in the spec for DSA
+                if ((keySize != 3072) && (keySize != 2048) &&
+                        ((keySize > 1024) || ((keySize & 0x3f) != 0))) {
+                    throw new InvalidAlgorithmParameterException(
+                        "DSA key must be multiples of 64 if less than " +
+                        "1024 bits, or 2048, 3072 bits. " +
+                        "The specific key size " +
+                        keySize + " is not supported");
                 }
             }
         }
     }
 
     // see JCA spec
+    @Override
     public KeyPair generateKeyPair() {
         token.ensureValid();
         CK_ATTRIBUTE[] publicKeyTemplate;
--- a/src/share/classes/sun/security/provider/DSAKeyPairGenerator.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/security/provider/DSAKeyPairGenerator.java	Tue Jan 16 22:58:44 2018 -0800
@@ -75,6 +75,8 @@
             // N=160
         } else if (sizeP == 2048 && (sizeQ == 224 || sizeQ == 256)) {
             // L=2048, N=224 or 256
+        } else if (sizeP == 3072 && sizeQ == 256) {
+            // L=3072, N=256
         } else {
             throw new InvalidParameterException
                 ("Unsupported prime and subprime size combination: " +
--- a/src/share/classes/sun/security/provider/DSAParameterGenerator.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/security/provider/DSAParameterGenerator.java	Tue Jan 16 22:58:44 2018 -0800
@@ -68,7 +68,6 @@
     private SecureRandom random;
 
     // useful constants
-    private static final BigInteger ZERO = BigInteger.valueOf(0);
     private static final BigInteger ONE = BigInteger.valueOf(1);
     private static final BigInteger TWO = BigInteger.valueOf(2);
 
@@ -84,11 +83,16 @@
      */
     @Override
     protected void engineInit(int strength, SecureRandom random) {
-        if ((strength != 2048) &&
-            ((strength < 512) || (strength > 1024) || (strength % 64 != 0))) {
+        if ((strength >= 512) && (strength <= 1024) && (strength % 64 == 0)) {
+            this.valueN = 160;
+        } else if (strength == 2048) {
+            this.valueN = 224;
+        } else if (strength == 3072) {
+            this.valueN = 256;
+        } else {
             throw new InvalidParameterException(
-                "Unexpected strength (size of prime): " + strength +
-                ". Prime size should be 512-1024, or 2048");
+                "Unexpected strength (size of prime): " + strength + ". " +
+                "Prime size should be 512 - 1024, or 2048, 3072");
         }
         this.valueL = strength;
         this.valueN = getDefDSASubprimeSize(strength);
@@ -114,13 +118,9 @@
             throw new InvalidAlgorithmParameterException("Invalid parameter");
         }
         DSAGenParameterSpec dsaGenParams = (DSAGenParameterSpec)genParamSpec;
-        int primePLen = dsaGenParams.getPrimePLength();
-        if (primePLen > 2048) {
-            throw new InvalidParameterException
-                ("No support for prime size " + primePLen);
-        }
+
         // directly initialize using the already validated values
-        this.valueL = primePLen;
+        this.valueL = dsaGenParams.getPrimePLength();
         this.valueN = dsaGenParams.getSubprimeQLength();
         this.seedLen = dsaGenParams.getSeedLength();
         this.random = random;
@@ -131,6 +131,7 @@
      *
      * @return the new AlgorithmParameters object
      */
+    @Override
     protected AlgorithmParameters engineGenerateParameters() {
         AlgorithmParameters algParams = null;
         try {
@@ -204,11 +205,13 @@
         int b = (valueL - 1) % outLen;
         byte[] seedBytes = new byte[seedLen/8];
         BigInteger twoSl = TWO.pow(seedLen);
-        int primeCertainty = -1;
+        int primeCertainty = 80; // for 1024-bit prime P
         if (valueL <= 1024) {
             primeCertainty = 80;
         } else if (valueL == 2048) {
             primeCertainty = 112;
+        } else if (valueL == 3072) {
+            primeCertainty = 128;
         }
 
         if (primeCertainty < 0) {
@@ -227,7 +230,10 @@
                     mod(TWO.pow(valueN - 1));
 
                 /* Step 7 */
-                resultQ = TWO.pow(valueN - 1).add(U).add(ONE). subtract(U.mod(TWO));
+                resultQ = TWO.pow(valueN - 1)
+                            .add(U)
+                            .add(ONE)
+                            .subtract(U.mod(TWO));
             } while (!resultQ.isProbablePrime(primeCertainty));
 
             /* Step 10 */
@@ -247,7 +253,8 @@
                 for (int i = 1; i < n; i++) {
                     W = W.add(V[i].multiply(TWO.pow(i * outLen)));
                 }
-                W = W.add((V[n].mod(TWO.pow(b))).multiply(TWO.pow(n * outLen)));
+                W = W.add((V[n].mod(TWO.pow(b)))
+                               .multiply(TWO.pow(n * outLen)));
                 /* Step 11.3 */
                 BigInteger twoLm1 = TWO.pow(valueL - 1);
                 BigInteger X = W.add(twoLm1);
--- a/src/share/classes/sun/security/provider/ParameterCache.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/security/provider/ParameterCache.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, 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
@@ -65,7 +65,7 @@
         // case#1: (512 <= p <= 1024) AND q=160
         // case#2: p=2048 AND q=224
         // case#3: p=2048 AND q=256
-        // (NOT-YET-SUPPORTED)case#4: p=3072 AND q=256
+        // case#4: p=3072 AND q=256
         return dsaCache.get(Integer.valueOf(primeLen+subprimeLen));
     }
 
@@ -90,6 +90,8 @@
             return getDSAParameterSpec(primeLen, 160, random);
         } else if (primeLen == 2048) {
             return getDSAParameterSpec(primeLen, 224, random);
+        } else if (primeLen == 3072) {
+            return getDSAParameterSpec(primeLen, 256, random);
         } else {
             return null;
         }
@@ -165,8 +167,8 @@
 
         /*
          * We support precomputed parameter for legacy 512, 768 bit moduli,
-         * and (L, N) combinations of (1024, 160), (2048, 224), (2048, 256).
-         * In this file we provide both the seed and counter
+         * and (L, N) combinations of (1024, 160), (2048, 224), (2048, 256),
+         * (3072, 256). In this file we provide both the seed and counter
          * value of the generation process for each of these seeds,
          * for validation purposes. We also include the test vectors
          * from the DSA specification, FIPS 186, and the FIPS 186
@@ -288,12 +290,14 @@
                            "af02112b0d1f02da30973224fe27aeda8b9d4b2922" +
                            "d9ba8be39ed9e103a63c52810bc688b7e2ed4316e1" +
                            "ef17dbde", 16);
+
         dsaCache.put(Integer.valueOf(2048+224),
                      new DSAParameterSpec(p2048_224, q2048_224, g2048_224));
 
         /*
          * L = 2048, N = 256
-         * SEED = b0b4417601b59cbc9d8ac8f935cadaec4f5fbb2f23785609ae466748d9b5a536
+         * SEED = b0b4417601b59cbc9d8ac8f935cadaec \
+         *        4f5fbb2f23785609ae466748d9b5a536
          * counter = 497
          */
         BigInteger p2048_256 =
@@ -329,14 +333,245 @@
                            "8d15bbac65212a55239cfc7e58fae38d7250ab9991" +
                            "ffbc97134025fe8ce04c4399ad96569be91a546f49" +
                            "78693c7a", 16);
+
         dsaCache.put(Integer.valueOf(2048+256),
                                 new DSAParameterSpec(p2048_256, q2048_256, g2048_256));
 
-        // use DSA parameters for DH as well
+
+        /*
+         * L = 3072, N = 256
+         * SEED = 9fe304be4d6b9919559f39d5911d12e9 \
+         *        5158d6946598cd59775b8f3b8fff3a3f
+         * counter = 1186
+         */
+        BigInteger p3072_256 = new BigInteger(
+                "ea9cda9f5fbda66dd830494609405687ab7cf38538e058d1" +
+                "e2f68dea95364866e1c05beacded24227edee28cad80bcec" +
+                "ad39913be3b713267b3b96c8d9f0f6a03b5dfc9222d5cfe4" +
+                "afcc9982f33784f760c3b759aebe3bbe9098a6b84c96f1fd" +
+                "e44ce11c084c2a082c7a76a0ef142928b4f328406ab9beb2" +
+                "4f84577dd0f46ce86fd8f08488269998bf4742d6425f7a0e" +
+                "c75d8660c5dd6f4e3b3d3bee81b2c21afe8c9e8b84b87192" +
+                "e2cc20f961d2bcd8133afcf3675ab80681cb374c78f33e29" +
+                "d1011083d89f9c5728b94676fccb1b57bc60288c15d85ae8" +
+                "38ae1941c5a20ae2b2049b3583fe30da455ddb3e6ad9b995" +
+                "5cd9bb5681431622beb0f92da533fcab496cebc447aa1bb5" +
+                "a8039522f2da98ff416289323a64df626ab6881870927dce" +
+                "e387f13b5c9d24d6cba1d82ed375a082506ee87bc7ae3006" +
+                "7f4a94e2ee363d992c40f2725b5db4b3525ebde22bbbfd0f" +
+                "a124a588b0f5a4acb3a86951aff09f8c8198fb5b53da0c93" +
+                "1cedc598b4f835b779d04d99026c7ba08c4b27f118ac1e3d", 16);
+
+        BigInteger q3072_256 = new BigInteger(
+                "c4eeac2bbab79bd831946d717a56a6e687547aa8e9c5494a" +
+                "5a4b2f4ca13d6c11", 16);
+
+        BigInteger g3072_256 = new BigInteger(
+                "42e5fa7844f8fa9d8998d830d004e7b15b1d276bcbe5f12c" +
+                "35ec90c1a25f5832018a6724bd9cdbe803b675509bed167f" +
+                "3d7cf8599fc865c6d5a0f79158c1bc918f00a944d0ad0f38" +
+                "f520fb91d85d82674d0d5f874faa5fcdfe56cd178c1afdc7" +
+                "ce8795727b7dee966ed0b3c5cedcef8aca628befebf2d105" +
+                "c7aff8eb0da9c9610737dd64dce1237b82c1b2bc8608d55f" +
+                "fda98d7189444e65883315669c05716bde36c78b130aa3df" +
+                "2e4d609914c7c8dc470f4e300187c775f81e7b1a9c0dce40" +
+                "5d6eab2cbb9d9c4ef44412ba573dd403c4ed7bc2364772f5" +
+                "6a30c48de78f5003f9371c55262d2c8ac2246ade3b02fdcf" +
+                "cf5cbfde74fbcbfe6e0e0fdf3160764f84d311c179a40af6" +
+                "79a8f47ab13c8f706893245eb11edcce451fa2ab98001998" +
+                "7f125d8dc96622d419ba0d71f16c6024dce9d364c3b26d8e" +
+                "c1a3c828f6c9d14b1d0333b95db77bfdbe3c6bce5337a1a5" +
+                "a7ace10111219448447197e2a344cc423be768bb89e27be6" +
+                "cbd22085614a5a3360be23b1bfbb6e6e6471363d32c85d31", 16);
+
+        dsaCache.put(Integer.valueOf(3072+256),
+                new DSAParameterSpec(p3072_256, q3072_256, g3072_256));
+
+        //
+        // Diffie-Hellman Groups
+        //
+
+        // the common generator
+        BigInteger dhG = BigInteger.valueOf(2);
+
+        //
+        // From RFC 7296
+
+        // The prime is: 2^768 - 2 ^704 - 1 + 2^64 * { [2^638 pi] + 149686 }
+        BigInteger dhP768 = new BigInteger(
+                "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" +
+                "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" +
+                "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" +
+                "E485B576625E7EC6F44C42E9A63A3620FFFFFFFFFFFFFFFF", 16);
+
+        // The prime is 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }
+        BigInteger dhP1024 = new BigInteger(
+                "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" +
+                "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" +
+                "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" +
+                "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" +
+                "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381" +
+                "FFFFFFFFFFFFFFFF", 16);
+
+        //
+        // From RFC 3526
+
+        // The prime is: 2^1536 - 2^1472 - 1 + 2^64 * { [2^1406 pi] + 741804 }
+        BigInteger dhP1536 = new BigInteger(
+                "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" +
+                "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" +
+                "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" +
+                "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" +
+                "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" +
+                "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" +
+                "83655D23DCA3AD961C62F356208552BB9ED529077096966D" +
+                "670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF", 16);
+
+        // This prime is: 2^2048 - 2^1984 - 1 + 2^64 * { [2^1918 pi] + 124476 }
+        BigInteger dhP2048 = new BigInteger(
+                "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" +
+                "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" +
+                "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" +
+                "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" +
+                "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" +
+                "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" +
+                "83655D23DCA3AD961C62F356208552BB9ED529077096966D" +
+                "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" +
+                "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" +
+                "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" +
+                "15728E5A8AACAA68FFFFFFFFFFFFFFFF", 16);
+
+        // This prime is: 2^3072 - 2^3008 - 1 + 2^64 * { [2^2942 pi] + 1690314 }
+        BigInteger dhP3072 = new BigInteger(
+                "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" +
+                "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" +
+                "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" +
+                "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" +
+                "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" +
+                "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" +
+                "83655D23DCA3AD961C62F356208552BB9ED529077096966D" +
+                "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" +
+                "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" +
+                "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" +
+                "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" +
+                "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" +
+                "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" +
+                "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" +
+                "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" +
+                "43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF", 16);
+
+        // This prime is: 2^4096 - 2^4032 - 1 + 2^64 * { [2^3966 pi] + 240904 }
+        BigInteger dhP4096 = new BigInteger(
+                "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" +
+                "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" +
+                "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" +
+                "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" +
+                "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" +
+                "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" +
+                "83655D23DCA3AD961C62F356208552BB9ED529077096966D" +
+                "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" +
+                "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" +
+                "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" +
+                "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" +
+                "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" +
+                "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" +
+                "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" +
+                "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" +
+                "43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7" +
+                "88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA" +
+                "2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6" +
+                "287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED" +
+                "1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9" +
+                "93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199" +
+                "FFFFFFFFFFFFFFFF", 16);
+
+        // This prime is: 2^6144 - 2^6080 - 1 + 2^64 * { [2^6014 pi] + 929484 }
+        BigInteger dhP6144 = new BigInteger(
+                "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08" +
+                "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B" +
+                "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9" +
+                "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6" +
+                "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8" +
+                "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D" +
+                "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C" +
+                "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718" +
+                "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D" +
+                "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D" +
+                "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226" +
+                "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C" +
+                "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC" +
+                "E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26" +
+                "99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB" +
+                "04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2" +
+                "233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127" +
+                "D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492" +
+                "36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406" +
+                "AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918" +
+                "DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B33205151" +
+                "2BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03" +
+                "F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97F" +
+                "BEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA" +
+                "CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58B" +
+                "B7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632" +
+                "387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E" +
+                "6DCC4024FFFFFFFFFFFFFFFF", 16);
+
+        // This prime is: 2^8192 - 2^8128 - 1 + 2^64 * { [2^8062 pi] + 4743158 }
+        BigInteger dhP8192 = new BigInteger(
+                "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" +
+                "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" +
+                "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" +
+                "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" +
+                "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" +
+                "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" +
+                "83655D23DCA3AD961C62F356208552BB9ED529077096966D" +
+                "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" +
+                "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" +
+                "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" +
+                "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" +
+                "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" +
+                "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" +
+                "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" +
+                "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" +
+                "43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7" +
+                "88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA" +
+                "2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6" +
+                "287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED" +
+                "1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9" +
+                "93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492" +
+                "36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BD" +
+                "F8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831" +
+                "179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1B" +
+                "DB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF" +
+                "5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6" +
+                "D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F3" +
+                "23A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA" +
+                "CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE328" +
+                "06A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55C" +
+                "DA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE" +
+                "12BF2D5B0B7474D6E694F91E6DBE115974A3926F12FEE5E4" +
+                "38777CB6A932DF8CD8BEC4D073B931BA3BC832B68D9DD300" +
+                "741FA7BF8AFC47ED2576F6936BA424663AAB639C5AE4F568" +
+                "3423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD9" +
+                "22222E04A4037C0713EB57A81A23F0C73473FC646CEA306B" +
+                "4BCBC8862F8385DDFA9D4B7FA2C087E879683303ED5BDD3A" +
+                "062B3CF5B3A278A66D2A13F83F44F82DDF310EE074AB6A36" +
+                "4597E899A0255DC164F31CC50846851DF9AB48195DED7EA1" +
+                "B1D510BD7EE74D73FAF36BC31ECFA268359046F4EB879F92" +
+                "4009438B481C6CD7889A002ED5EE382BC9190DA6FC026E47" +
+                "9558E4475677E9AA9E3050E2765694DFC81F56E880B96E71" +
+                "60C980DD98EDD3DFFFFFFFFFFFFFFFFF", 16);
+
+        // use DSA parameters for DH for sizes not defined in RFC 7296, 3526
         dhCache.put(Integer.valueOf(512), new DHParameterSpec(p512, g512));
-        dhCache.put(Integer.valueOf(768), new DHParameterSpec(p768, g768));
-        dhCache.put(Integer.valueOf(1024), new DHParameterSpec(p1024, g1024));
-        dhCache.put(Integer.valueOf(2048), new DHParameterSpec(p2048_224, g2048_224));
+
+        dhCache.put(Integer.valueOf(768), new DHParameterSpec(dhP768, dhG));
+        dhCache.put(Integer.valueOf(1024), new DHParameterSpec(dhP1024, dhG));
+        dhCache.put(Integer.valueOf(1536), new DHParameterSpec(dhP1536, dhG));
+        dhCache.put(Integer.valueOf(2048), new DHParameterSpec(dhP2048, dhG));
+        dhCache.put(Integer.valueOf(3072), new DHParameterSpec(dhP3072, dhG));
+        dhCache.put(Integer.valueOf(4096), new DHParameterSpec(dhP4096, dhG));
+        dhCache.put(Integer.valueOf(6144), new DHParameterSpec(dhP6144, dhG));
+        dhCache.put(Integer.valueOf(8192), new DHParameterSpec(dhP8192, dhG));
     }
-
 }
--- a/src/share/classes/sun/security/provider/certpath/ldap/LDAPCertStore.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/security/provider/certpath/ldap/LDAPCertStore.java	Tue Jan 16 22:58:44 2018 -0800
@@ -31,6 +31,8 @@
 import java.net.URI;
 import java.util.*;
 import javax.naming.Context;
+import javax.naming.CompositeName;
+import javax.naming.InvalidNameException;
 import javax.naming.NamingEnumeration;
 import javax.naming.NamingException;
 import javax.naming.NameNotFoundException;
@@ -43,8 +45,10 @@
 import java.security.*;
 import java.security.cert.Certificate;
 import java.security.cert.*;
+import javax.naming.ldap.LdapContext;
 import javax.security.auth.x500.X500Principal;
 
+import com.sun.jndi.ldap.LdapReferralException;
 import sun.misc.HexDumpEncoder;
 import sun.security.provider.certpath.X509CertificatePair;
 import sun.security.util.Cache;
@@ -220,6 +224,12 @@
         certStoreCache = Cache.newSoftMemoryCache(185);
     static synchronized CertStore getInstance(LDAPCertStoreParameters params)
         throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
+
+        SecurityManager security = System.getSecurityManager();
+        if (security != null) {
+            security.checkConnect(params.getServerName(), params.getPort());
+        }
+
         CertStore lcs = certStoreCache.get(params);
         if (lcs == null) {
             lcs = CertStore.getInstance("LDAP", params);
@@ -265,7 +275,7 @@
              */
             Hashtable<?,?> currentEnv = ctx.getEnvironment();
             if (currentEnv.get(Context.REFERRAL) == null) {
-                ctx.addToEnvironment(Context.REFERRAL, "follow-scheme");
+                ctx.addToEnvironment(Context.REFERRAL, "throw");
             }
         } catch (NamingException e) {
             if (debug != null) {
@@ -302,11 +312,25 @@
         private Map<String, byte[][]> valueMap;
         private final List<String> requestedAttributes;
 
-        LDAPRequest(String name) {
-            this.name = name;
+        LDAPRequest(String name) throws CertStoreException {
+            this.name = checkName(name);
             requestedAttributes = new ArrayList<>(5);
         }
 
+        private String checkName(String name) throws CertStoreException {
+            if (name == null) {
+                throw new CertStoreException("Name absent");
+            }
+            try {
+                if (new CompositeName(name).size() > 1) {
+                    throw new CertStoreException("Invalid name: " + name);
+                }
+            } catch (InvalidNameException ine) {
+                throw new CertStoreException("Invalid name: " + name, ine);
+            }
+            return name;
+        }
+
         String getName() {
             return name;
         }
@@ -321,7 +345,6 @@
         /**
          * Gets one or more binary values from an attribute.
          *
-         * @param name          the location holding the attribute
          * @param attrId                the attribute identifier
          * @return                      an array of binary values (byte arrays)
          * @throws NamingException      if a naming exception occurs
@@ -373,6 +396,39 @@
             Attributes attrs;
             try {
                 attrs = ctx.getAttributes(name, attrIds);
+            } catch (LdapReferralException lre) {
+                // LdapCtx has a hopCount field to avoid infinite loop
+                while (true) {
+                    try {
+                        String newName = (String) lre.getReferralInfo();
+                        URI newUri = new URI(newName);
+                        if (!newUri.getScheme().equalsIgnoreCase("ldap")) {
+                            throw new IllegalArgumentException("Not LDAP");
+                        }
+                        String newDn = newUri.getPath();
+                        if (newDn != null && newDn.charAt(0) == '/') {
+                            newDn = newDn.substring(1);
+                        }
+                        checkName(newDn);
+                    } catch (Exception e) {
+                        throw new NamingException("Cannot follow referral to "
+                                + lre.getReferralInfo());
+                    }
+                    LdapContext refCtx =
+                            (LdapContext)lre.getReferralContext();
+
+                    // repeat the original operation at the new context
+                    try {
+                        attrs = refCtx.getAttributes(name, attrIds);
+                        break;
+                    } catch (LdapReferralException re) {
+                        lre = re;
+                        continue;
+                    } finally {
+                        // Make sure we close referral context
+                        refCtx.close();
+                    }
+                }
             } catch (NameNotFoundException e) {
                 // name does not exist on this LDAP server
                 // treat same as not attributes found
--- a/src/share/classes/sun/security/rsa/RSAPublicKeyImpl.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/security/rsa/RSAPublicKeyImpl.java	Tue Jan 16 22:58:44 2018 -0800
@@ -48,6 +48,7 @@
 public final class RSAPublicKeyImpl extends X509Key implements RSAPublicKey {
 
     private static final long serialVersionUID = 2644735423591199609L;
+    private static final BigInteger THREE = BigInteger.valueOf(3);
 
     private BigInteger n;       // modulus
     private BigInteger e;       // public exponent
@@ -61,6 +62,7 @@
         this.n = n;
         this.e = e;
         RSAKeyFactory.checkRSAProviderKeyLengths(n.bitLength(), e);
+        checkExponentRange();
         // generate the encoding
         algid = RSAPrivateCrtKeyImpl.rsaId;
         try {
@@ -83,6 +85,19 @@
     public RSAPublicKeyImpl(byte[] encoded) throws InvalidKeyException {
         decode(encoded);
         RSAKeyFactory.checkRSAProviderKeyLengths(n.bitLength(), e);
+        checkExponentRange();
+    }
+
+    private void checkExponentRange() throws InvalidKeyException {
+        // the exponent should be smaller than the modulus
+        if (e.compareTo(n) >= 0) {
+            throw new InvalidKeyException("exponent is larger than modulus");
+        }
+
+        // the exponent should be at least 3
+        if (e.compareTo(THREE) < 0) {
+            throw new InvalidKeyException("exponent is smaller than 3");
+        }
     }
 
     // see JCA doc
--- a/src/share/classes/sun/security/ssl/ClientHandshaker.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/security/ssl/ClientHandshaker.java	Tue Jan 16 22:58:44 2018 -0800
@@ -633,6 +633,54 @@
             }
         }
 
+        // check the "extended_master_secret" extension
+        ExtendedMasterSecretExtension extendedMasterSecretExt =
+                (ExtendedMasterSecretExtension)mesg.extensions.get(
+                        ExtensionType.EXT_EXTENDED_MASTER_SECRET);
+        if (extendedMasterSecretExt != null) {
+            // Is it the expected server extension?
+            if (!useExtendedMasterSecret ||
+                    !(mesgVersion.v >= ProtocolVersion.TLS10.v) || !requestedToUseEMS) {
+                fatalSE(Alerts.alert_unsupported_extension,
+                        "Server sent the extended_master_secret " +
+                        "extension improperly");
+            }
+
+            // For abbreviated handshake, if the original session did not use
+            // the "extended_master_secret" extension but the new ServerHello
+            // contains the extension, the client MUST abort the handshake.
+            if (resumingSession && (session != null) &&
+                    !session.getUseExtendedMasterSecret()) {
+                fatalSE(Alerts.alert_unsupported_extension,
+                        "Server sent an unexpected extended_master_secret " +
+                        "extension on session resumption");
+            }
+        } else {
+            if (useExtendedMasterSecret && !allowLegacyMasterSecret) {
+                // For full handshake, if a client receives a ServerHello
+                // without the extension, it SHOULD abort the handshake if
+                // it does not wish to interoperate with legacy servers.
+                fatalSE(Alerts.alert_handshake_failure,
+                    "Extended Master Secret extension is required");
+            }
+
+            if (resumingSession && (session != null)) {
+                if (session.getUseExtendedMasterSecret()) {
+                    // For abbreviated handshake, if the original session used
+                    // the "extended_master_secret" extension but the new
+                    // ServerHello does not contain the extension, the client
+                    // MUST abort the handshake.
+                    fatalSE(Alerts.alert_handshake_failure,
+                            "Missing Extended Master Secret extension " +
+                            "on session resumption");
+                } else if (useExtendedMasterSecret && !allowLegacyResumption) {
+                    // Unlikely, abbreviated handshake should be discarded.
+                    fatalSE(Alerts.alert_handshake_failure,
+                        "Extended Master Secret extension is required");
+                }
+            }
+        }
+
         if (resumingSession && session != null) {
             setHandshakeSessionSE(session);
             // Reserve the handshake state if this is a session-resumption
@@ -652,7 +700,8 @@
             } else if ((type != ExtensionType.EXT_ELLIPTIC_CURVES)
                     && (type != ExtensionType.EXT_EC_POINT_FORMATS)
                     && (type != ExtensionType.EXT_SERVER_NAME)
-                    && (type != ExtensionType.EXT_RENEGOTIATION_INFO)) {
+                    && (type != ExtensionType.EXT_RENEGOTIATION_INFO)
+                    && (type != ExtensionType.EXT_EXTENDED_MASTER_SECRET)){
                 fatalSE(Alerts.alert_unsupported_extension,
                     "Server sent an unsupported extension: " + type);
             }
@@ -661,7 +710,8 @@
         // Create a new session, we need to do the full handshake
         session = new SSLSessionImpl(protocolVersion, cipherSuite,
                             getLocalSupportedSignAlgs(),
-                            mesg.sessionId, getHostSE(), getPortSE());
+                            mesg.sessionId, getHostSE(), getPortSE(),
+                            (extendedMasterSecretExt != null));
         session.setRequestedServerNames(requestedServerNames);
         setHandshakeSessionSE(session);
         if (debug != null && Debug.isOn("handshake")) {
@@ -1297,6 +1347,44 @@
                 session = null;
             }
 
+            if ((session != null) && useExtendedMasterSecret) {
+                boolean isTLS10Plus = sessionVersion.v >= ProtocolVersion.TLS10.v;
+                if (isTLS10Plus && !session.getUseExtendedMasterSecret()) {
+                    if (!allowLegacyResumption) {
+                        // perform full handshake instead
+                        //
+                        // The client SHOULD NOT offer an abbreviated handshake
+                        // to resume a session that does not use an extended
+                        // master secret.  Instead, it SHOULD offer a full
+                        // handshake.
+                        session = null;
+                    }
+                }
+
+                if ((session != null) && !allowUnsafeServerCertChange) {
+                    // It is fine to move on with abbreviate handshake if
+                    // endpoint identification is enabled.
+                    String identityAlg = getEndpointIdentificationAlgorithmSE();
+                    if ((identityAlg == null || identityAlg.length() == 0)) {
+                        if (isTLS10Plus) {
+                            if (!session.getUseExtendedMasterSecret()) {
+                                // perform full handshake instead
+                                session = null;
+                            }   // Otherwise, use extended master secret.
+                        } else {
+                            // The extended master secret extension does not
+                            // apply to SSL 3.0.  Perform a full handshake
+                            // instead.
+                            //
+                            // Note that the useExtendedMasterSecret is
+                            // extended to protect SSL 3.0 connections,
+                            // by discarding abbreviate handshake.
+                            session = null;
+                        }
+                    }
+                }
+            }
+
             if (session != null) {
                 if (debug != null) {
                     if (Debug.isOn("handshake") || Debug.isOn("session")) {
@@ -1381,12 +1469,12 @@
 
         // add elliptic curves and point format extensions
         if (cipherSuites.containsEC()) {
-            SupportedEllipticCurvesExtension ece =
-                SupportedEllipticCurvesExtension.createExtension(algorithmConstraints);
+            EllipticCurvesExtension ece =
+                EllipticCurvesExtension.createExtension(algorithmConstraints);
             if (ece != null) {
                 clientHelloMessage.extensions.add(ece);
                 clientHelloMessage.extensions.add(
-                   SupportedEllipticPointFormatsExtension.DEFAULT);
+                   EllipticPointFormatsExtension.DEFAULT);
             }
         }
 
@@ -1403,6 +1491,14 @@
             clientHelloMessage.addSignatureAlgorithmsExtension(localSignAlgs);
         }
 
+        // add Extended Master Secret extension
+        if (useExtendedMasterSecret && (maxProtocolVersion.v >= ProtocolVersion.TLS10.v)) {
+            if ((session == null) || session.getUseExtendedMasterSecret()) {
+                clientHelloMessage.addExtendedMasterSecretExtension();
+                requestedToUseEMS = true;
+            }
+        }
+
         // add server_name extension
         if (enableSNIExtension) {
             if (session != null) {
@@ -1463,10 +1559,14 @@
         // Allow server certificate change in client side during renegotiation
         // after a session-resumption abbreviated initial handshake?
         //
-        // DO NOT need to check allowUnsafeServerCertChange here. We only
+        // DO NOT need to check allowUnsafeServerCertChange here.  We only
         // reserve server certificates when allowUnsafeServerCertChange is
         // flase.
-        if (reservedServerCerts != null) {
+        //
+        // Allow server certificate change if it is negotiated to use the
+        // extended master secret.
+        if ((reservedServerCerts != null) &&
+                !session.getUseExtendedMasterSecret()) {
             // It is not necessary to check the certificate update if endpoint
             // identification is enabled.
             String identityAlg = getEndpointIdentificationAlgorithmSE();
--- a/src/share/classes/sun/security/ssl/DHCrypt.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/security/ssl/DHCrypt.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2017, 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
@@ -151,7 +151,7 @@
                                     params.getP(), params.getG());
         }
         try {
-            KeyFactory factory = JsseJce.getKeyFactory("DH");
+            KeyFactory factory = JsseJce.getKeyFactory("DiffieHellman");
             return factory.getKeySpec(key, DHPublicKeySpec.class);
         } catch (Exception e) {
             throw new RuntimeException(e);
@@ -302,7 +302,16 @@
                 "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" +
                 "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381" +
                 "FFFFFFFFFFFFFFFF", 16);
-        private static final BigInteger p2048 = new BigInteger(  // TLS FEDHE
+        private static final BigInteger p1536 = new BigInteger(  // RFC 3526
+                "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" +
+                "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" +
+                "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" +
+                "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" +
+                "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" +
+                "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" +
+                "83655D23DCA3AD961C62F356208552BB9ED529077096966D" +
+                "670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF", 16);
+        private static final BigInteger p2048 = new BigInteger(  // TLS FFDHE
                 "FFFFFFFFFFFFFFFFADF85458A2BB4A9AAFDC5620273D3CF1" +
                 "D8B9C583CE2D3695A9E13641146433FBCC939DCE249B3EF9" +
                 "7D2FE363630C75D8F681B202AEC4617AD3DF1ED5D5FD6561" +
@@ -314,9 +323,126 @@
                 "9172FE9CE98583FF8E4F1232EEF28183C3FE3B1B4C6FAD73" +
                 "3BB5FCBC2EC22005C58EF1837D1683B2C6F34A26C1B2EFFA" +
                 "886B423861285C97FFFFFFFFFFFFFFFF", 16);
+        private static final BigInteger p3072 = new BigInteger(  // TLS FFDHE
+                "FFFFFFFFFFFFFFFFADF85458A2BB4A9AAFDC5620273D3CF1" +
+                "D8B9C583CE2D3695A9E13641146433FBCC939DCE249B3EF9" +
+                "7D2FE363630C75D8F681B202AEC4617AD3DF1ED5D5FD6561" +
+                "2433F51F5F066ED0856365553DED1AF3B557135E7F57C935" +
+                "984F0C70E0E68B77E2A689DAF3EFE8721DF158A136ADE735" +
+                "30ACCA4F483A797ABC0AB182B324FB61D108A94BB2C8E3FB" +
+                "B96ADAB760D7F4681D4F42A3DE394DF4AE56EDE76372BB19" +
+                "0B07A7C8EE0A6D709E02FCE1CDF7E2ECC03404CD28342F61" +
+                "9172FE9CE98583FF8E4F1232EEF28183C3FE3B1B4C6FAD73" +
+                "3BB5FCBC2EC22005C58EF1837D1683B2C6F34A26C1B2EFFA" +
+                "886B4238611FCFDCDE355B3B6519035BBC34F4DEF99C0238" +
+                "61B46FC9D6E6C9077AD91D2691F7F7EE598CB0FAC186D91C" +
+                "AEFE130985139270B4130C93BC437944F4FD4452E2D74DD3" +
+                "64F2E21E71F54BFF5CAE82AB9C9DF69EE86D2BC522363A0D" +
+                "ABC521979B0DEADA1DBF9A42D5C4484E0ABCD06BFA53DDEF" +
+                "3C1B20EE3FD59D7C25E41D2B66C62E37FFFFFFFFFFFFFFFF", 16);
+        private static final BigInteger p4096 = new BigInteger(  // TLS FFDHE
+                "FFFFFFFFFFFFFFFFADF85458A2BB4A9AAFDC5620273D3CF1" +
+                "D8B9C583CE2D3695A9E13641146433FBCC939DCE249B3EF9" +
+                "7D2FE363630C75D8F681B202AEC4617AD3DF1ED5D5FD6561" +
+                "2433F51F5F066ED0856365553DED1AF3B557135E7F57C935" +
+                "984F0C70E0E68B77E2A689DAF3EFE8721DF158A136ADE735" +
+                "30ACCA4F483A797ABC0AB182B324FB61D108A94BB2C8E3FB" +
+                "B96ADAB760D7F4681D4F42A3DE394DF4AE56EDE76372BB19" +
+                "0B07A7C8EE0A6D709E02FCE1CDF7E2ECC03404CD28342F61" +
+                "9172FE9CE98583FF8E4F1232EEF28183C3FE3B1B4C6FAD73" +
+                "3BB5FCBC2EC22005C58EF1837D1683B2C6F34A26C1B2EFFA" +
+                "886B4238611FCFDCDE355B3B6519035BBC34F4DEF99C0238" +
+                "61B46FC9D6E6C9077AD91D2691F7F7EE598CB0FAC186D91C" +
+                "AEFE130985139270B4130C93BC437944F4FD4452E2D74DD3" +
+                "64F2E21E71F54BFF5CAE82AB9C9DF69EE86D2BC522363A0D" +
+                "ABC521979B0DEADA1DBF9A42D5C4484E0ABCD06BFA53DDEF" +
+                "3C1B20EE3FD59D7C25E41D2B669E1EF16E6F52C3164DF4FB" +
+                "7930E9E4E58857B6AC7D5F42D69F6D187763CF1D55034004" +
+                "87F55BA57E31CC7A7135C886EFB4318AED6A1E012D9E6832" +
+                "A907600A918130C46DC778F971AD0038092999A333CB8B7A" +
+                "1A1DB93D7140003C2A4ECEA9F98D0ACC0A8291CDCEC97DCF" +
+                "8EC9B55A7F88A46B4DB5A851F44182E1C68A007E5E655F6A" +
+                "FFFFFFFFFFFFFFFF", 16);
+        private static final BigInteger p6144 = new BigInteger(  // TLS FFDHE
+                "FFFFFFFFFFFFFFFFADF85458A2BB4A9AAFDC5620273D3CF1" +
+                "D8B9C583CE2D3695A9E13641146433FBCC939DCE249B3EF9" +
+                "7D2FE363630C75D8F681B202AEC4617AD3DF1ED5D5FD6561" +
+                "2433F51F5F066ED0856365553DED1AF3B557135E7F57C935" +
+                "984F0C70E0E68B77E2A689DAF3EFE8721DF158A136ADE735" +
+                "30ACCA4F483A797ABC0AB182B324FB61D108A94BB2C8E3FB" +
+                "B96ADAB760D7F4681D4F42A3DE394DF4AE56EDE76372BB19" +
+                "0B07A7C8EE0A6D709E02FCE1CDF7E2ECC03404CD28342F61" +
+                "9172FE9CE98583FF8E4F1232EEF28183C3FE3B1B4C6FAD73" +
+                "3BB5FCBC2EC22005C58EF1837D1683B2C6F34A26C1B2EFFA" +
+                "886B4238611FCFDCDE355B3B6519035BBC34F4DEF99C0238" +
+                "61B46FC9D6E6C9077AD91D2691F7F7EE598CB0FAC186D91C" +
+                "AEFE130985139270B4130C93BC437944F4FD4452E2D74DD3" +
+                "64F2E21E71F54BFF5CAE82AB9C9DF69EE86D2BC522363A0D" +
+                "ABC521979B0DEADA1DBF9A42D5C4484E0ABCD06BFA53DDEF" +
+                "3C1B20EE3FD59D7C25E41D2B669E1EF16E6F52C3164DF4FB" +
+                "7930E9E4E58857B6AC7D5F42D69F6D187763CF1D55034004" +
+                "87F55BA57E31CC7A7135C886EFB4318AED6A1E012D9E6832" +
+                "A907600A918130C46DC778F971AD0038092999A333CB8B7A" +
+                "1A1DB93D7140003C2A4ECEA9F98D0ACC0A8291CDCEC97DCF" +
+                "8EC9B55A7F88A46B4DB5A851F44182E1C68A007E5E0DD902" +
+                "0BFD64B645036C7A4E677D2C38532A3A23BA4442CAF53EA6" +
+                "3BB454329B7624C8917BDD64B1C0FD4CB38E8C334C701C3A" +
+                "CDAD0657FCCFEC719B1F5C3E4E46041F388147FB4CFDB477" +
+                "A52471F7A9A96910B855322EDB6340D8A00EF092350511E3" +
+                "0ABEC1FFF9E3A26E7FB29F8C183023C3587E38DA0077D9B4" +
+                "763E4E4B94B2BBC194C6651E77CAF992EEAAC0232A281BF6" +
+                "B3A739C1226116820AE8DB5847A67CBEF9C9091B462D538C" +
+                "D72B03746AE77F5E62292C311562A846505DC82DB854338A" +
+                "E49F5235C95B91178CCF2DD5CACEF403EC9D1810C6272B04" +
+                "5B3B71F9DC6B80D63FDD4A8E9ADB1E6962A69526D43161C1" +
+                "A41D570D7938DAD4A40E329CD0E40E65FFFFFFFFFFFFFFFF", 16);
+        private static final BigInteger p8192 = new BigInteger(  // TLS FFDHE
+                "FFFFFFFFFFFFFFFFADF85458A2BB4A9AAFDC5620273D3CF1" +
+                "D8B9C583CE2D3695A9E13641146433FBCC939DCE249B3EF9" +
+                "7D2FE363630C75D8F681B202AEC4617AD3DF1ED5D5FD6561" +
+                "2433F51F5F066ED0856365553DED1AF3B557135E7F57C935" +
+                "984F0C70E0E68B77E2A689DAF3EFE8721DF158A136ADE735" +
+                "30ACCA4F483A797ABC0AB182B324FB61D108A94BB2C8E3FB" +
+                "B96ADAB760D7F4681D4F42A3DE394DF4AE56EDE76372BB19" +
+                "0B07A7C8EE0A6D709E02FCE1CDF7E2ECC03404CD28342F61" +
+                "9172FE9CE98583FF8E4F1232EEF28183C3FE3B1B4C6FAD73" +
+                "3BB5FCBC2EC22005C58EF1837D1683B2C6F34A26C1B2EFFA" +
+                "886B4238611FCFDCDE355B3B6519035BBC34F4DEF99C0238" +
+                "61B46FC9D6E6C9077AD91D2691F7F7EE598CB0FAC186D91C" +
+                "AEFE130985139270B4130C93BC437944F4FD4452E2D74DD3" +
+                "64F2E21E71F54BFF5CAE82AB9C9DF69EE86D2BC522363A0D" +
+                "ABC521979B0DEADA1DBF9A42D5C4484E0ABCD06BFA53DDEF" +
+                "3C1B20EE3FD59D7C25E41D2B669E1EF16E6F52C3164DF4FB" +
+                "7930E9E4E58857B6AC7D5F42D69F6D187763CF1D55034004" +
+                "87F55BA57E31CC7A7135C886EFB4318AED6A1E012D9E6832" +
+                "A907600A918130C46DC778F971AD0038092999A333CB8B7A" +
+                "1A1DB93D7140003C2A4ECEA9F98D0ACC0A8291CDCEC97DCF" +
+                "8EC9B55A7F88A46B4DB5A851F44182E1C68A007E5E0DD902" +
+                "0BFD64B645036C7A4E677D2C38532A3A23BA4442CAF53EA6" +
+                "3BB454329B7624C8917BDD64B1C0FD4CB38E8C334C701C3A" +
+                "CDAD0657FCCFEC719B1F5C3E4E46041F388147FB4CFDB477" +
+                "A52471F7A9A96910B855322EDB6340D8A00EF092350511E3" +
+                "0ABEC1FFF9E3A26E7FB29F8C183023C3587E38DA0077D9B4" +
+                "763E4E4B94B2BBC194C6651E77CAF992EEAAC0232A281BF6" +
+                "B3A739C1226116820AE8DB5847A67CBEF9C9091B462D538C" +
+                "D72B03746AE77F5E62292C311562A846505DC82DB854338A" +
+                "E49F5235C95B91178CCF2DD5CACEF403EC9D1810C6272B04" +
+                "5B3B71F9DC6B80D63FDD4A8E9ADB1E6962A69526D43161C1" +
+                "A41D570D7938DAD4A40E329CCFF46AAA36AD004CF600C838" +
+                "1E425A31D951AE64FDB23FCEC9509D43687FEB69EDD1CC5E" +
+                "0B8CC3BDF64B10EF86B63142A3AB8829555B2F747C932665" +
+                "CB2C0F1CC01BD70229388839D2AF05E454504AC78B758282" +
+                "2846C0BA35C35F5C59160CC046FD8251541FC68C9C86B022" +
+                "BB7099876A460E7451A8A93109703FEE1C217E6C3826E52C" +
+                "51AA691E0E423CFC99E9E31650C1217B624816CDAD9A95F9" +
+                "D5B8019488D9C0A0A1FE3075A577E23183F81D4A3F2FA457" +
+                "1EFC8CE0BA8A4FE8B6855DFE72B0A66EDED2FBABFBE58A30" +
+                "FAFABE1C5D71A87E2F741EF8C1FE86FEA6BBFDE530677F0D" +
+                "97D11D49F7A8443D0822E506A9F4614E011E2A94838FF88C" +
+                "D68C8BB7C5C6424CFFFFFFFFFFFFFFFF", 16);
 
         private static final BigInteger[] supportedPrimes = {
-                p512, p768, p1024, p2048};
+                p512, p768, p1024, p1536, p2048, p3072, p4096, p6144, p8192};
 
         // a measure of the uncertainty that prime modulus p is not a prime
         //
--- a/src/share/classes/sun/security/ssl/ECDHCrypt.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/security/ssl/ECDHCrypt.java	Tue Jan 16 22:58:44 2018 -0800
@@ -60,7 +60,7 @@
         try {
             KeyPairGenerator kpg = JsseJce.getKeyPairGenerator("EC");
             ECGenParameterSpec params =
-                    SupportedEllipticCurvesExtension.getECGenParamSpec(curveId);
+                    EllipticCurvesExtension.getECGenParamSpec(curveId);
             kpg.initialize(params, random);
             KeyPair kp = kpg.generateKeyPair();
             privateKey = kp.getPrivate();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/sun/security/ssl/EllipticCurvesExtension.java	Tue Jan 16 22:58:44 2018 -0800
@@ -0,0 +1,397 @@
+/*
+ * Copyright (c) 2006, 2017, 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * 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.
+ */
+
+package sun.security.ssl;
+
+import java.io.IOException;
+import java.security.spec.ECParameterSpec;
+import java.security.spec.ECGenParameterSpec;
+import java.security.spec.InvalidParameterSpecException;
+import java.security.AlgorithmParameters;
+import java.security.AlgorithmConstraints;
+import java.security.CryptoPrimitive;
+import java.security.AccessController;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.ArrayList;
+import javax.net.ssl.SSLProtocolException;
+
+import sun.security.action.GetPropertyAction;
+
+final class EllipticCurvesExtension extends HelloExtension {
+
+    /* Class and subclass dynamic debugging support */
+    private static final Debug debug = Debug.getInstance("ssl");
+
+    private static final int ARBITRARY_PRIME = 0xff01;
+    private static final int ARBITRARY_CHAR2 = 0xff02;
+
+    // speed up the searching
+    private static final Map<String, Integer> oidToIdMap = new HashMap<>();
+    private static final Map<Integer, String> idToOidMap = new HashMap<>();
+
+    // speed up the parameters construction
+    private static final Map<Integer,
+                AlgorithmParameters> idToParams = new HashMap<>();
+
+    // the supported elliptic curves
+    private static final int[] supportedCurveIds;
+
+    // the curves of the extension
+    private final int[] curveIds;
+
+    // See sun.security.util.CurveDB for the OIDs
+    private static enum NamedEllipticCurve {
+        T163_K1(1,  "sect163k1",    "1.3.132.0.1",      true),  // NIST K-163
+        T163_R1(2,  "sect163r1",    "1.3.132.0.2",      false),
+        T163_R2(3,  "sect163r2",    "1.3.132.0.15",     true),  // NIST B-163
+        T193_R1(4,  "sect193r1",    "1.3.132.0.24",     false),
+        T193_R2(5,  "sect193r2",    "1.3.132.0.25",     false),
+        T233_K1(6,  "sect233k1",    "1.3.132.0.26",     true),  // NIST K-233
+        T233_R1(7,  "sect233r1",    "1.3.132.0.27",     true),  // NIST B-233
+        T239_K1(8,  "sect239k1",    "1.3.132.0.3",      false),
+        T283_K1(9,  "sect283k1",    "1.3.132.0.16",     true),  // NIST K-283
+        T283_R1(10, "sect283r1",    "1.3.132.0.17",     true),  // NIST B-283
+        T409_K1(11, "sect409k1",    "1.3.132.0.36",     true),  // NIST K-409
+        T409_R1(12, "sect409r1",    "1.3.132.0.37",     true),  // NIST B-409
+        T571_K1(13, "sect571k1",    "1.3.132.0.38",     true),  // NIST K-571
+        T571_R1(14, "sect571r1",    "1.3.132.0.39",     true),  // NIST B-571
+
+        P160_K1(15, "secp160k1",    "1.3.132.0.9",      false),
+        P160_R1(16, "secp160r1",    "1.3.132.0.8",      false),
+        P160_R2(17, "secp160r2",    "1.3.132.0.30",     false),
+        P192_K1(18, "secp192k1",    "1.3.132.0.31",     false),
+        P192_R1(19, "secp192r1",    "1.2.840.10045.3.1.1", true), // NIST P-192
+        P224_K1(20, "secp224k1",    "1.3.132.0.32",     false),
+        P224_R1(21, "secp224r1",    "1.3.132.0.33",     true),  // NIST P-224
+        P256_K1(22, "secp256k1",    "1.3.132.0.10",     false),
+        P256_R1(23, "secp256r1",    "1.2.840.10045.3.1.7", true), // NIST P-256
+        P384_R1(24, "secp384r1",    "1.3.132.0.34",     true),  // NIST P-384
+        P521_R1(25, "secp521r1",    "1.3.132.0.35",     true);  // NIST P-521
+
+        int          id;
+        String       name;
+        String       oid;
+        boolean      isFips;
+
+        NamedEllipticCurve(int id, String name, String oid, boolean isFips) {
+            this.id = id;
+            this.name = name;
+            this.oid = oid;
+            this.isFips = isFips;
+
+            if (oidToIdMap.put(oid, id) != null ||
+                idToOidMap.put(id, oid) != null) {
+
+                throw new RuntimeException(
+                        "Duplicate named elliptic curve definition: " + name);
+            }
+        }
+
+        static NamedEllipticCurve getCurve(String name, boolean requireFips) {
+            for (NamedEllipticCurve curve : NamedEllipticCurve.values()) {
+                if (curve.name.equals(name) && (!requireFips || curve.isFips)) {
+                    return curve;
+                }
+            }
+
+            return null;
+        }
+    }
+
+    static {
+        boolean requireFips = SunJSSE.isFIPS();
+
+        // hack code to initialize NamedEllipticCurve
+        NamedEllipticCurve nec =
+                NamedEllipticCurve.getCurve("secp256r1", false);
+
+        // The value of the System Property defines a list of enabled named
+        // curves in preference order, separated with comma.  For example:
+        //
+        //      jdk.tls.namedGroups="secp521r1, secp256r1, secp384r1"
+        //
+        // If the System Property is not defined or the value is empty, the
+        // default curves and preferences will be used.
+        String property = AccessController.doPrivileged(
+                    new GetPropertyAction("jdk.tls.namedGroups"));
+        if (property != null && property.length() != 0) {
+            // remove double quote marks from beginning/end of the property
+            if (property.length() > 1 && property.charAt(0) == '"' &&
+                    property.charAt(property.length() - 1) == '"') {
+                property = property.substring(1, property.length() - 1);
+            }
+        }
+
+        ArrayList<Integer> idList;
+        if (property != null && property.length() != 0) {   // customized curves
+            String[] curves = property.split(",");
+            idList = new ArrayList<>(curves.length);
+            for (String curve : curves) {
+                curve = curve.trim();
+                if (!curve.isEmpty()) {
+                    NamedEllipticCurve namedCurve =
+                            NamedEllipticCurve.getCurve(curve, requireFips);
+                    if (namedCurve != null) {
+                        if (isAvailableCurve(namedCurve.id)) {
+                            idList.add(namedCurve.id);
+                        }
+                    }   // ignore unknown curves
+                }
+            }
+            if (idList.isEmpty() && JsseJce.isEcAvailable()) {
+                throw new IllegalArgumentException(
+                    "System property jdk.tls.namedGroups(" + property + ") " +
+                    "contains no supported elliptic curves");
+            }
+        } else {        // default curves
+            int[] ids;
+            if (requireFips) {
+                ids = new int[] {
+                    // only NIST curves in FIPS mode
+                    23, 24, 25, 9, 10, 11, 12, 13, 14,
+                };
+            } else {
+                ids = new int[] {
+                    // NIST curves first
+                    23, 24, 25, 9, 10, 11, 12, 13, 14,
+                    // non-NIST curves
+                    22,
+                };
+            }
+
+            idList = new ArrayList<>(ids.length);
+            for (int curveId : ids) {
+                if (isAvailableCurve(curveId)) {
+                    idList.add(curveId);
+                }
+            }
+        }
+
+        if (debug != null && idList.isEmpty()) {
+            debug.println(
+                "Initialized [jdk.tls.namedGroups|default] list contains " +
+                "no available elliptic curves. " +
+                (property != null ? "(" + property + ")" : "[Default]"));
+        }
+
+            supportedCurveIds = new int[idList.size()];
+            int i = 0;
+            for (Integer id : idList) {
+                supportedCurveIds[i++] = id;
+            }
+        }
+
+    // check whether the curve is supported by the underlying providers
+    private static boolean isAvailableCurve(int curveId) {
+        String oid = idToOidMap.get(curveId);
+        if (oid != null) {
+            AlgorithmParameters params = null;
+            try {
+                params = JsseJce.getAlgorithmParameters("EC");
+                params.init(new ECGenParameterSpec(oid));
+            } catch (Exception e) {
+                return false;
+            }
+
+            // cache the parameters
+            idToParams.put(curveId, params);
+
+            return true;
+        }
+
+        return false;
+    }
+
+    private EllipticCurvesExtension(int[] curveIds) {
+        super(ExtensionType.EXT_ELLIPTIC_CURVES);
+        this.curveIds = curveIds;
+    }
+
+    EllipticCurvesExtension(HandshakeInStream s, int len)
+            throws IOException {
+        super(ExtensionType.EXT_ELLIPTIC_CURVES);
+        int k = s.getInt16();
+        if (((len & 1) != 0) || (k + 2 != len)) {
+            throw new SSLProtocolException("Invalid " + type + " extension");
+        }
+
+        // Note: unknown curves will be ignored later.
+        curveIds = new int[k >> 1];
+        for (int i = 0; i < curveIds.length; i++) {
+            curveIds[i] = s.getInt16();
+        }
+    }
+
+    // get the preferred active curve
+    static int getActiveCurves(AlgorithmConstraints constraints) {
+        return getPreferredCurve(supportedCurveIds, constraints);
+    }
+
+    static boolean hasActiveCurves(AlgorithmConstraints constraints) {
+        return getActiveCurves(constraints) >= 0;
+    }
+
+    static EllipticCurvesExtension createExtension(
+                AlgorithmConstraints constraints) {
+
+        ArrayList<Integer> idList = new ArrayList<>(supportedCurveIds.length);
+        for (int curveId : supportedCurveIds) {
+            if (constraints.permits(
+                    EnumSet.of(CryptoPrimitive.KEY_AGREEMENT),
+                                "EC", idToParams.get(curveId))) {
+                idList.add(curveId);
+            }
+        }
+
+        if (!idList.isEmpty()) {
+            int[] ids = new int[idList.size()];
+            int i = 0;
+            for (Integer id : idList) {
+                ids[i++] = id;
+            }
+
+            return new EllipticCurvesExtension(ids);
+        }
+
+        return null;
+    }
+
+    // get the preferred activated curve
+    int getPreferredCurve(AlgorithmConstraints constraints) {
+        return getPreferredCurve(curveIds, constraints);
+    }
+
+    // get a preferred activated curve
+    private static int getPreferredCurve(int[] curves,
+                AlgorithmConstraints constraints) {
+        for (int curveId : curves) {
+            if (isSupported(curveId) && constraints.permits(
+                    EnumSet.of(CryptoPrimitive.KEY_AGREEMENT),
+                                "EC", idToParams.get(curveId))) {
+                return curveId;
+            }
+        }
+
+        return -1;
+    }
+
+    boolean contains(int index) {
+        for (int curveId : curveIds) {
+            if (index == curveId) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    @Override
+    int length() {
+        return 6 + (curveIds.length << 1);
+    }
+
+    @Override
+    void send(HandshakeOutStream s) throws IOException {
+        s.putInt16(type.id);
+        int k = curveIds.length << 1;
+        s.putInt16(k + 2);
+        s.putInt16(k);
+        for (int curveId : curveIds) {
+            s.putInt16(curveId);
+        }
+    }
+
+    @Override
+    public String toString() {
+        StringBuilder sb = new StringBuilder();
+        sb.append("Extension " + type + ", curve names: {");
+        boolean first = true;
+        for (int curveId : curveIds) {
+            if (first) {
+                first = false;
+            } else {
+                sb.append(", ");
+            }
+            String curveName = getCurveName(curveId);
+            if (curveName != null) {
+                sb.append(curveName);
+            } else if (curveId == ARBITRARY_PRIME) {
+                sb.append("arbitrary_explicit_prime_curves");
+            } else if (curveId == ARBITRARY_CHAR2) {
+                sb.append("arbitrary_explicit_char2_curves");
+            } else {
+                sb.append("unknown curve " + curveId);
+            }
+        }
+        sb.append("}");
+        return sb.toString();
+    }
+
+    // Test whether the given curve is supported.
+    static boolean isSupported(int index) {
+        for (int curveId : supportedCurveIds) {
+            if (index == curveId) {
+                return true;
+            }
+        }
+
+        return false;
+    }
+
+    static int getCurveIndex(ECParameterSpec params) {
+        String oid = JsseJce.getNamedCurveOid(params);
+        if (oid == null) {
+            return -1;
+        }
+        Integer n = oidToIdMap.get(oid);
+        return (n == null) ? -1 : n;
+    }
+
+    static String getCurveOid(int index) {
+        return idToOidMap.get(index);
+    }
+
+    static ECGenParameterSpec getECGenParamSpec(int index) {
+        AlgorithmParameters params = idToParams.get(index);
+        try {
+            return params.getParameterSpec(ECGenParameterSpec.class);
+        } catch (InvalidParameterSpecException ipse) {
+            // should be unlikely
+            String curveOid = getCurveOid(index);
+            return new ECGenParameterSpec(curveOid);
+        }
+    }
+
+    private static String getCurveName(int index) {
+        for (NamedEllipticCurve namedCurve : NamedEllipticCurve.values()) {
+            if (namedCurve.id == index) {
+                return namedCurve.name;
+            }
+        }
+
+        return null;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/sun/security/ssl/EllipticPointFormatsExtension.java	Tue Jan 16 22:58:44 2018 -0800
@@ -0,0 +1,104 @@
+/*
+ * Copyright (c) 2006, 2016, 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * 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.
+ */
+
+package sun.security.ssl;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.net.ssl.SSLProtocolException;
+
+final class EllipticPointFormatsExtension extends HelloExtension {
+
+    final static int FMT_UNCOMPRESSED = 0;
+    final static int FMT_ANSIX962_COMPRESSED_PRIME = 1;
+    final static int FMT_ANSIX962_COMPRESSED_CHAR2 = 2;
+
+    static final HelloExtension DEFAULT =
+        new EllipticPointFormatsExtension(
+            new byte[] {FMT_UNCOMPRESSED});
+
+    private final byte[] formats;
+
+    private EllipticPointFormatsExtension(byte[] formats) {
+        super(ExtensionType.EXT_EC_POINT_FORMATS);
+        this.formats = formats;
+    }
+
+    EllipticPointFormatsExtension(HandshakeInStream s, int len)
+            throws IOException {
+        super(ExtensionType.EXT_EC_POINT_FORMATS);
+        formats = s.getBytes8();
+        // RFC 4492 says uncompressed points must always be supported.
+        // Check just to make sure.
+        boolean uncompressed = false;
+        for (int format : formats) {
+            if (format == FMT_UNCOMPRESSED) {
+                uncompressed = true;
+                break;
+            }
+        }
+        if (uncompressed == false) {
+            throw new SSLProtocolException
+                ("Peer does not support uncompressed points");
+        }
+    }
+
+    @Override
+    int length() {
+        return 5 + formats.length;
+    }
+
+    @Override
+    void send(HandshakeOutStream s) throws IOException {
+        s.putInt16(type.id);
+        s.putInt16(formats.length + 1);
+        s.putBytes8(formats);
+    }
+
+    private static String toString(byte format) {
+        int f = format & 0xff;
+        switch (f) {
+        case FMT_UNCOMPRESSED:
+            return "uncompressed";
+        case FMT_ANSIX962_COMPRESSED_PRIME:
+            return "ansiX962_compressed_prime";
+        case FMT_ANSIX962_COMPRESSED_CHAR2:
+            return "ansiX962_compressed_char2";
+        default:
+            return "unknown-" + f;
+        }
+    }
+
+    @Override
+    public String toString() {
+        List<String> list = new ArrayList<String>();
+        for (byte format : formats) {
+            list.add(toString(format));
+        }
+        return "Extension " + type + ", formats: " + list;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/sun/security/ssl/ExtendedMasterSecretExtension.java	Tue Jan 16 22:58:44 2018 -0800
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2017, Red Hat, Inc. and/or its affiliates.
+ *
+ * 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.
+ */
+
+package sun.security.ssl;
+
+import java.io.IOException;
+import javax.net.ssl.SSLProtocolException;
+
+/**
+ * Extended Master Secret TLS extension (TLS 1.0+). This extension
+ * defines how to calculate the TLS connection master secret and
+ * mitigates some types of man-in-the-middle attacks.
+ *
+ * See further information in
+ * <a href="https://tools.ietf.org/html/rfc7627">RFC 7627</a>.
+ *
+ * @author Martin Balao (mbalao@redhat.com)
+ */
+final class ExtendedMasterSecretExtension extends HelloExtension {
+    ExtendedMasterSecretExtension() {
+        super(ExtensionType.EXT_EXTENDED_MASTER_SECRET);
+    }
+
+    ExtendedMasterSecretExtension(HandshakeInStream s,
+            int len) throws IOException {
+        super(ExtensionType.EXT_EXTENDED_MASTER_SECRET);
+
+        if (len != 0) {
+            throw new SSLProtocolException("Invalid " + type + " extension");
+        }
+    }
+
+    @Override
+    int length() {
+        return 4;       // 4: extension type and length fields
+    }
+
+    @Override
+    void send(HandshakeOutStream s) throws IOException {
+        s.putInt16(type.id);    // ExtensionType extension_type;
+        s.putInt16(0);          // extension_data length
+    }
+
+    @Override
+    public String toString() {
+        return "Extension " + type;
+    }
+}
+
--- a/src/share/classes/sun/security/ssl/ExtensionType.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/security/ssl/ExtensionType.java	Tue Jan 16 22:58:44 2018 -0800
@@ -43,7 +43,7 @@
         return name;
     }
 
-    static List<ExtensionType> knownExtensions = new ArrayList<ExtensionType>(9);
+    static List<ExtensionType> knownExtensions = new ArrayList<ExtensionType>(14);
 
     static ExtensionType get(int id) {
         for (ExtensionType ext : knownExtensions) {
@@ -96,6 +96,10 @@
     final static ExtensionType EXT_SIGNATURE_ALGORITHMS =
             e(0x000D, "signature_algorithms");   // IANA registry value: 13
 
+    // extensions defined in RFC 7627
+    static final ExtensionType EXT_EXTENDED_MASTER_SECRET =
+            e(0x0017, "extended_master_secret"); // IANA registry value: 23
+
     // extensions defined in RFC 5746
     final static ExtensionType EXT_RENEGOTIATION_INFO =
             e(0xff01, "renegotiation_info");     // IANA registry value: 65281
--- a/src/share/classes/sun/security/ssl/HandshakeHash.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/security/ssl/HandshakeHash.java	Tue Jan 16 22:58:44 2018 -0800
@@ -104,7 +104,29 @@
      * a hash for the certificate verify message is required.
      */
     HandshakeHash(boolean needCertificateVerify) {
-        clonesNeeded = needCertificateVerify ? 3 : 2;
+        // We may rework the code later, but for now we use hard-coded number
+        // of clones if the underlying MessageDigests are not cloneable.
+        //
+        // The number used here is based on the current handshake protocols and
+        // implementation.  It may be changed if the handshake processe gets
+        // changed in the future, for example adding a new extension that
+        // requires handshake hash.  Please be careful about the number of
+        // clones if additional handshak hash is required in the future.
+        //
+        // For the current implementation, the handshake hash is required for
+        // the following items:
+        //     . CertificateVerify handshake message (optional)
+        //     . client Finished handshake message
+        //     . server Finished Handshake message
+        //     . the extended Master Secret extension [RFC 7627]
+        //
+        // Note that a late call to server setNeedClientAuth dose not update
+        // the number of clones.  We may address the issue later.
+        //
+        // Note for safe, we allocate one more clone for the current
+        // implementation.  We may consider it more carefully in the future
+        // for the exactly number or rework the code in a different way.
+        clonesNeeded = needCertificateVerify ? 5 : 4;
     }
 
     void update(byte[] b, int offset, int len) {
@@ -226,7 +248,8 @@
         if (finMD != null) return;
 
         try {
-            finMD = CloneableDigest.getDigest(normalizeAlgName(s), 2);
+            // See comment in the contructor.
+            finMD = CloneableDigest.getDigest(normalizeAlgName(s), 4);
         } catch (NoSuchAlgorithmException e) {
             throw new Error(e);
         }
--- a/src/share/classes/sun/security/ssl/HandshakeMessage.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/security/ssl/HandshakeMessage.java	Tue Jan 16 22:58:44 2018 -0800
@@ -274,6 +274,10 @@
         extensions.add(signatureAlgorithm);
     }
 
+    void addExtendedMasterSecretExtension() {
+        extensions.add(new ExtendedMasterSecretExtension());
+    }
+
     @Override
     int messageType() { return ht_client_hello; }
 
@@ -1010,7 +1014,7 @@
         ECParameterSpec params = publicKey.getParams();
         ECPoint point = publicKey.getW();
         pointBytes = JsseJce.encodePoint(point, params.getCurve());
-        curveId = SupportedEllipticCurvesExtension.getCurveIndex(params);
+        curveId = EllipticCurvesExtension.getCurveIndex(params);
 
         if (privateKey == null) {
             // ECDH_anon
@@ -1024,7 +1028,7 @@
         } else {
             sig = getSignature(privateKey.getAlgorithm());
         }
-        sig.initSign(privateKey);  // where is the SecureRandom?
+        sig.initSign(privateKey, sr);
 
         updateSignature(sig, clntNonce, svrNonce);
         signatureBytes = sig.sign();
@@ -1048,13 +1052,11 @@
         // the supported curves during the exchange of the Hello messages.
         if (curveType == CURVE_NAMED_CURVE) {
             curveId = input.getInt16();
-            if (SupportedEllipticCurvesExtension.isSupported(curveId)
-                    == false) {
+            if (!EllipticCurvesExtension.isSupported(curveId)) {
                 throw new SSLHandshakeException(
                     "Unsupported curveId: " + curveId);
             }
-            String curveOid =
-                SupportedEllipticCurvesExtension.getCurveOid(curveId);
+            String curveOid = EllipticCurvesExtension.getCurveOid(curveId);
             if (curveOid == null) {
                 throw new SSLHandshakeException(
                     "Unknown named curve: " + curveId);
--- a/src/share/classes/sun/security/ssl/Handshaker.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/security/ssl/Handshaker.java	Tue Jan 16 22:58:44 2018 -0800
@@ -29,12 +29,6 @@
 import java.io.*;
 import java.util.*;
 import java.security.*;
-import java.security.NoSuchAlgorithmException;
-import java.security.AccessController;
-import java.security.AlgorithmConstraints;
-import java.security.AccessControlContext;
-import java.security.PrivilegedExceptionAction;
-import java.security.PrivilegedActionException;
 
 import javax.crypto.*;
 import javax.crypto.spec.*;
@@ -204,9 +198,41 @@
             Debug.getBooleanProperty(
                 "jdk.tls.rejectClientInitiatedRenegotiation", false);
 
+    // To switch off the extended_master_secret extension.
+    static final boolean useExtendedMasterSecret;
+
+    // Allow session resumption without Extended Master Secret extension.
+    static final boolean allowLegacyResumption =
+            Debug.getBooleanProperty("jdk.tls.allowLegacyResumption", true);
+
+    // Allow full handshake without Extended Master Secret extension.
+    static final boolean allowLegacyMasterSecret =
+            Debug.getBooleanProperty("jdk.tls.allowLegacyMasterSecret", true);
+
+    // Is it requested to use extended master secret extension?
+    boolean requestedToUseEMS = false;
+
     // need to dispose the object when it is invalidated
     boolean invalidated;
 
+    // Is the extended_master_secret extension supported?
+    static {
+        boolean supportExtendedMasterSecret = true;
+        try {
+            KeyGenerator kg =
+                JsseJce.getKeyGenerator("SunTlsExtendedMasterSecret");
+        } catch (NoSuchAlgorithmException nae) {
+            supportExtendedMasterSecret = false;
+        }
+
+        if (supportExtendedMasterSecret) {
+            useExtendedMasterSecret = Debug.getBooleanProperty(
+                    "jdk.tls.useExtendedMasterSecret", true);
+        } else {
+            useExtendedMasterSecret = false;
+        }
+    }
+
     Handshaker(SSLSocketImpl c, SSLContextImpl context,
             ProtocolList enabledProtocols, boolean needCertVerify,
             boolean isClient, ProtocolVersion activeProtocolVersion,
@@ -216,7 +242,7 @@
         init(context, enabledProtocols, needCertVerify, isClient,
             activeProtocolVersion, isInitialHandshake, secureRenegotiation,
             clientVerifyData, serverVerifyData);
-    }
+   }
 
     Handshaker(SSLEngineImpl engine, SSLContextImpl context,
             ProtocolList enabledProtocols, boolean needCertVerify,
@@ -647,7 +673,7 @@
                             boolean available = true;
                             if (suite.keyExchange.isEC) {
                                 if (!checkedCurves) {
-                                    hasCurves = SupportedEllipticCurvesExtension
+                                    hasCurves = EllipticCurvesExtension
                                         .hasActiveCurves(algorithmConstraints);
                                     checkedCurves = true;
 
@@ -738,7 +764,7 @@
                             boolean available = true;
                             if (suite.keyExchange.isEC) {
                                 if (!checkedCurves) {
-                                    hasCurves = SupportedEllipticCurvesExtension
+                                    hasCurves = EllipticCurvesExtension
                                         .hasActiveCurves(algorithmConstraints);
                                     checkedCurves = true;
 
@@ -1169,6 +1195,7 @@
      * SHA1 hashes are of (different) constant strings, the pre-master
      * secret, and the nonces provided by the client and the server.
      */
+    @SuppressWarnings("deprecation")
     private SecretKey calculateMasterSecret(SecretKey preMasterSecret,
             ProtocolVersion requestedVersion) {
 
@@ -1200,10 +1227,34 @@
         int prfHashLength = prf.getPRFHashLength();
         int prfBlockSize = prf.getPRFBlockSize();
 
-        TlsMasterSecretParameterSpec spec = new TlsMasterSecretParameterSpec(
-                preMasterSecret, protocolVersion.major, protocolVersion.minor,
-                clnt_random.random_bytes, svr_random.random_bytes,
-                prfHashAlg, prfHashLength, prfBlockSize);
+        TlsMasterSecretParameterSpec spec;
+        if (session.getUseExtendedMasterSecret()) {
+            // reset to use the extended master secret algorithm
+            masterAlg = "SunTlsExtendedMasterSecret";
+
+            byte[] sessionHash = null;
+            if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
+                sessionHash = handshakeHash.getFinishedHash();
+            } else {
+                // TLS 1.0/1.1
+                sessionHash = new byte[36];
+                try {
+                    handshakeHash.getMD5Clone().digest(sessionHash, 0, 16);
+                    handshakeHash.getSHAClone().digest(sessionHash, 16, 20);
+                } catch (DigestException de) {
+                    throw new ProviderException(de);
+                }
+            }
+
+            spec = new TlsMasterSecretParameterSpec(
+                    preMasterSecret, protocolVersion.major, protocolVersion.minor,
+                    sessionHash, prfHashAlg, prfHashLength, prfBlockSize);
+        } else {
+            spec = new TlsMasterSecretParameterSpec(
+                    preMasterSecret, protocolVersion.major, protocolVersion.minor,
+                    clnt_random.random_bytes, svr_random.random_bytes,
+                    prfHashAlg, prfHashLength, prfBlockSize);
+        }
 
         try {
             KeyGenerator kg = JsseJce.getKeyGenerator(masterAlg);
--- a/src/share/classes/sun/security/ssl/HelloExtensions.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/security/ssl/HelloExtensions.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2006, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2006, 2016, 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
@@ -49,8 +49,8 @@
  *      explicitly support.
  *  . ServerNameExtension: the server_name extension.
  *  . SignatureAlgorithmsExtension: the signature_algorithms extension.
- *  . SupportedEllipticCurvesExtension: the ECC supported curves extension.
- *  . SupportedEllipticPointFormatsExtension: the ECC supported point formats
+ *  . EllipticCurvesExtension: the ECC supported curves extension.
+ *  . EllipticPointFormatsExtension: the ECC supported point formats
  *      (compressed/uncompressed) extension.
  *
  * @since   1.6
@@ -79,12 +79,13 @@
             } else if (extType == ExtensionType.EXT_SIGNATURE_ALGORITHMS) {
                 extension = new SignatureAlgorithmsExtension(s, extlen);
             } else if (extType == ExtensionType.EXT_ELLIPTIC_CURVES) {
-                extension = new SupportedEllipticCurvesExtension(s, extlen);
+                extension = new EllipticCurvesExtension(s, extlen);
             } else if (extType == ExtensionType.EXT_EC_POINT_FORMATS) {
-                extension =
-                        new SupportedEllipticPointFormatsExtension(s, extlen);
+                extension = new EllipticPointFormatsExtension(s, extlen);
             } else if (extType == ExtensionType.EXT_RENEGOTIATION_INFO) {
                 extension = new RenegotiationInfoExtension(s, extlen);
+            } else if (extType == ExtensionType.EXT_EXTENDED_MASTER_SECRET) {
+                extension = new ExtendedMasterSecretExtension(s, extlen);
             } else {
                 extension = new UnknownExtension(s, extlen, extType);
             }
--- a/src/share/classes/sun/security/ssl/SSLSessionImpl.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/security/ssl/SSLSessionImpl.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2017, 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
@@ -91,6 +91,7 @@
     private byte                compressionMethod;
     private CipherSuite         cipherSuite;
     private SecretKey           masterSecret;
+    private final boolean       useExtendedMasterSecret;
 
     /*
      * Information not part of the SSLv3 protocol spec, but used
@@ -145,7 +146,7 @@
      */
     private SSLSessionImpl() {
         this(ProtocolVersion.NONE, CipherSuite.C_NULL, null,
-            new SessionId(false, null), null, -1);
+            new SessionId(false, null), null, -1, false);
     }
 
     /*
@@ -155,9 +156,11 @@
      */
     SSLSessionImpl(ProtocolVersion protocolVersion, CipherSuite cipherSuite,
             Collection<SignatureAndHashAlgorithm> algorithms,
-            SecureRandom generator, String host, int port) {
+            SecureRandom generator, String host, int port,
+            boolean useExtendedMasterSecret) {
         this(protocolVersion, cipherSuite, algorithms,
-             new SessionId(defaultRejoinable, generator), host, port);
+             new SessionId(defaultRejoinable, generator), host, port,
+             useExtendedMasterSecret);
     }
 
     /*
@@ -165,7 +168,8 @@
      */
     SSLSessionImpl(ProtocolVersion protocolVersion, CipherSuite cipherSuite,
             Collection<SignatureAndHashAlgorithm> algorithms,
-            SessionId id, String host, int port) {
+            SessionId id, String host, int port,
+            boolean useExtendedMasterSecret) {
         this.protocolVersion = protocolVersion;
         sessionId = id;
         peerCerts = null;
@@ -177,6 +181,7 @@
         sessionCount = ++counter;
         localSupportedSignAlgs =
             SignatureAndHashAlgorithm.getAlgorithmNames(algorithms);
+        this.useExtendedMasterSecret = useExtendedMasterSecret;
 
         if (debug != null && Debug.isOn("session")) {
             System.out.println("%% Initialized:  " + this);
@@ -198,6 +203,10 @@
         return masterSecret;
     }
 
+    boolean getUseExtendedMasterSecret() {
+        return useExtendedMasterSecret;
+    }
+
     void setPeerCertificates(X509Certificate[] peer) {
         if (peerCerts == null) {
             peerCerts = peer;
--- a/src/share/classes/sun/security/ssl/ServerHandshaker.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/security/ssl/ServerHandshaker.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2017, 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
@@ -93,7 +93,7 @@
     private ProtocolVersion clientRequestedVersion;
 
     // client supported elliptic curves
-    private SupportedEllipticCurvesExtension requestedCurves;
+    private EllipticCurvesExtension requestedCurves;
 
     // the preferable signature algorithm used by ServerKeyExchange message
     SignatureAndHashAlgorithm preferableSignatureAlgorithm;
@@ -135,13 +135,17 @@
             useSmartEphemeralDHKeys = false;
 
             try {
+                // DH parameter generation can be extremely slow, best to
+                // use one of the supported pre-computed DH parameters
+                // (see DHCrypt class).
                 customizedDHKeySize = Integer.parseUnsignedInt(property);
-                if (customizedDHKeySize < 1024 || customizedDHKeySize > 2048) {
+                if (customizedDHKeySize < 1024 || customizedDHKeySize > 8192 ||
+                        (customizedDHKeySize & 0x3f) != 0) {
                     throw new IllegalArgumentException(
                         "Unsupported customized DH key size: " +
                         customizedDHKeySize + ". " +
-                        "The key size can only range from 1024" +
-                        " to 2048 (inclusive)");
+                        "The key size must be multiple of 64, " +
+                        "and can only range from 1024 to 8192 (inclusive)");
                 }
             } catch (NumberFormatException nfe) {
                 throw new IllegalArgumentException(
@@ -285,6 +289,11 @@
                         ("Unrecognized key exchange: " + keyExchange);
                 }
 
+                // Need to add the hash for RFC 7627.
+                if (session.getUseExtendedMasterSecret()) {
+                    input.digestNow();
+                }
+
                 //
                 // All keys are calculated from the premaster secret
                 // and the exchanged nonces in the same way.
@@ -491,6 +500,27 @@
             }
         }
 
+        // check out the "extended_master_secret" extension
+        if (useExtendedMasterSecret) {
+            ExtendedMasterSecretExtension extendedMasterSecretExtension =
+                    (ExtendedMasterSecretExtension)mesg.extensions.get(
+                            ExtensionType.EXT_EXTENDED_MASTER_SECRET);
+            if (extendedMasterSecretExtension != null) {
+                requestedToUseEMS = true;
+            } else if (mesg.protocolVersion.v >= ProtocolVersion.TLS10.v) {
+                if (!allowLegacyMasterSecret) {
+                    // For full handshake, if the server receives a ClientHello
+                    // without the extension, it SHOULD abort the handshake if
+                    // it does not wish to interoperate with legacy clients.
+                    //
+                    // As if extended master extension is required for full
+                    // handshake, it MUST be used in abbreviated handshake too.
+                    fatalSE(Alerts.alert_handshake_failure,
+                        "Extended Master Secret extension is required");
+                }
+            }
+        }
+
         /*
          * Always make sure this entire record has been digested before we
          * start emitting output, to ensure correct digesting order.
@@ -565,8 +595,42 @@
                 if (resumingSession) {
                     ProtocolVersion oldVersion = previous.getProtocolVersion();
                     // cannot resume session with different version
-                    if (oldVersion != protocolVersion) {
+                    if (oldVersion != mesg.protocolVersion) {
+                        resumingSession = false;
+                    }
+                }
+
+                if (resumingSession && useExtendedMasterSecret) {
+                    if (requestedToUseEMS &&
+                            !previous.getUseExtendedMasterSecret()) {
+                        // For abbreviated handshake request, If the original
+                        // session did not use the "extended_master_secret"
+                        // extension but the new ClientHello contains the
+                        // extension, then the server MUST NOT perform the
+                        // abbreviated handshake.  Instead, it SHOULD continue
+                        // with a full handshake.
                         resumingSession = false;
+                    } else if (!requestedToUseEMS &&
+                            previous.getUseExtendedMasterSecret()) {
+                        // For abbreviated handshake request, if the original
+                        // session used the "extended_master_secret" extension
+                        // but the new ClientHello does not contain it, the
+                        // server MUST abort the abbreviated handshake.
+                        fatalSE(Alerts.alert_handshake_failure,
+                                "Missing Extended Master Secret extension " +
+                                "on session resumption");
+                    } else if (!requestedToUseEMS &&
+                            !previous.getUseExtendedMasterSecret()) {
+                        // For abbreviated handshake request, if neither the
+                        // original session nor the new ClientHello uses the
+                        // extension, the server SHOULD abort the handshake.
+                        if (!allowLegacyResumption) {
+                            fatalSE(Alerts.alert_handshake_failure,
+                                "Missing Extended Master Secret extension " +
+                                "on session resumption");
+                        } else {  // Otherwise, continue with a full handshake.
+                            resumingSession = false;
+                        }
                     }
                 }
 
@@ -683,7 +747,7 @@
                 throw new SSLException("Client did not resume a session");
             }
 
-            requestedCurves = (SupportedEllipticCurvesExtension)
+            requestedCurves = (EllipticCurvesExtension)
                         mesg.extensions.get(ExtensionType.EXT_ELLIPTIC_CURVES);
 
             // We only need to handle the "signature_algorithm" extension
@@ -716,7 +780,9 @@
             session = new SSLSessionImpl(protocolVersion, CipherSuite.C_NULL,
                         getLocalSupportedSignAlgs(),
                         sslContext.getSecureRandom(),
-                        getHostAddressSE(), getPortSE());
+                        getHostAddressSE(), getPortSE(),
+                        (requestedToUseEMS &&
+                                (protocolVersion.v >= ProtocolVersion.TLS10.v)));
 
             if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
                 if (peerSupportedSignAlgs != null) {
@@ -781,6 +847,10 @@
             }
         }
 
+        if (session.getUseExtendedMasterSecret()) {
+            m1.extensions.add(new ExtendedMasterSecretExtension());
+        }
+
         if (debug != null && Debug.isOn("handshake")) {
             m1.print(System.out);
             System.out.println("Cipher suite:  " + session.getSuite());
@@ -1377,15 +1447,11 @@
          * Applications may also want to customize the ephemeral DH key size
          * to a fixed length for non-exportable cipher suites. This can be
          * approached by setting system property "jdk.tls.ephemeralDHKeySize"
-         * to a valid positive integer between 1024 and 2048 bits, inclusive.
+         * to a valid positive integer between 1024 and 8192 bits, inclusive.
          *
          * Note that the minimum acceptable key size is 1024 bits except
          * exportable cipher suites or legacy mode.
          *
-         * Note that the maximum acceptable key size is 2048 bits because
-         * DH keys bigger than 2048 are not always supported by underlying
-         * JCE providers.
-         *
          * Note that per RFC 2246, the key size limit of DH is 512 bits for
          * exportable cipher suites.  Because of the weakness, exportable
          * cipher suites are deprecated since TLS v1.1 and they are not
@@ -1400,10 +1466,17 @@
             } else if (useSmartEphemeralDHKeys) {    // matched mode
                 if (key != null) {
                     int ks = KeyUtil.getKeySize(key);
-                    // Note that SunJCE provider only supports 2048 bits DH
-                    // keys bigger than 1024.  Please DON'T use value other
-                    // than 1024 and 2048 at present.  We may improve the
-                    // underlying providers and key size here in the future.
+
+                    // DH parameter generation can be extremely slow, make
+                    // sure to use one of the supported pre-computed DH
+                    // parameters (see DHCrypt class).
+                    //
+                    // Old deployed applications may not be ready to support
+                    // DH key sizes bigger than 2048 bits.  Please DON'T use
+                    // value other than 1024 and 2048 at present.  May improve
+                    // the underlying providers and key size limit in the
+                    // future when the compatibility and interoperability
+                    // impact is limited.
                     //
                     // keySize = ks <= 1024 ? 1024 : (ks >= 2048 ? 2048 : ks);
                     keySize = ks <= 1024 ? 1024 : 2048;
@@ -1422,7 +1495,7 @@
     private boolean setupEphemeralECDHKeys() {
         int index = (requestedCurves != null) ?
                 requestedCurves.getPreferredCurve(algorithmConstraints) :
-                SupportedEllipticCurvesExtension.getActiveCurves(algorithmConstraints);
+                EllipticCurvesExtension.getActiveCurves(algorithmConstraints);
         if (index < 0) {
             // no match found, cannot use this ciphersuite
             return false;
@@ -1477,8 +1550,8 @@
                 return false;
             }
             ECParameterSpec params = ((ECPublicKey)publicKey).getParams();
-            int id = SupportedEllipticCurvesExtension.getCurveIndex(params);
-            if ((id <= 0) || !SupportedEllipticCurvesExtension.isSupported(id) ||
+            int id = EllipticCurvesExtension.getCurveIndex(params);
+            if ((id <= 0) || !EllipticCurvesExtension.isSupported(id) ||
                 ((requestedCurves != null) && !requestedCurves.contains(id))) {
                 return false;
             }
--- a/src/share/classes/sun/security/ssl/SupportedEllipticCurvesExtension.java	Mon Jan 08 22:36:23 2018 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,397 +0,0 @@
-/*
- * Copyright (c) 2006, 2017, 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.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * 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.
- */
-
-package sun.security.ssl;
-
-import java.io.IOException;
-import java.security.spec.ECParameterSpec;
-import java.security.spec.ECGenParameterSpec;
-import java.security.spec.InvalidParameterSpecException;
-import java.security.AlgorithmParameters;
-import java.security.AlgorithmConstraints;
-import java.security.CryptoPrimitive;
-import java.security.AccessController;
-import java.util.EnumSet;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.ArrayList;
-import javax.net.ssl.SSLProtocolException;
-
-import sun.security.action.GetPropertyAction;
-
-final class SupportedEllipticCurvesExtension extends HelloExtension {
-
-    /* Class and subclass dynamic debugging support */
-    private static final Debug debug = Debug.getInstance("ssl");
-
-    private static final int ARBITRARY_PRIME = 0xff01;
-    private static final int ARBITRARY_CHAR2 = 0xff02;
-
-    // speed up the searching
-    private static final Map<String, Integer> oidToIdMap = new HashMap<>();
-    private static final Map<Integer, String> idToOidMap = new HashMap<>();
-
-    // speed up the parameters construction
-    private static final Map<Integer,
-                AlgorithmParameters> idToParams = new HashMap<>();
-
-    // the supported elliptic curves
-    private static final int[] supportedCurveIds;
-
-    // the curves of the extension
-    private final int[] curveIds;
-
-    // See sun.security.util.CurveDB for the OIDs
-    private static enum NamedEllipticCurve {
-        T163_K1(1,  "sect163k1",    "1.3.132.0.1",      true),  // NIST K-163
-        T163_R1(2,  "sect163r1",    "1.3.132.0.2",      false),
-        T163_R2(3,  "sect163r2",    "1.3.132.0.15",     true),  // NIST B-163
-        T193_R1(4,  "sect193r1",    "1.3.132.0.24",     false),
-        T193_R2(5,  "sect193r2",    "1.3.132.0.25",     false),
-        T233_K1(6,  "sect233k1",    "1.3.132.0.26",     true),  // NIST K-233
-        T233_R1(7,  "sect233r1",    "1.3.132.0.27",     true),  // NIST B-233
-        T239_K1(8,  "sect239k1",    "1.3.132.0.3",      false),
-        T283_K1(9,  "sect283k1",    "1.3.132.0.16",     true),  // NIST K-283
-        T283_R1(10, "sect283r1",    "1.3.132.0.17",     true),  // NIST B-283
-        T409_K1(11, "sect409k1",    "1.3.132.0.36",     true),  // NIST K-409
-        T409_R1(12, "sect409r1",    "1.3.132.0.37",     true),  // NIST B-409
-        T571_K1(13, "sect571k1",    "1.3.132.0.38",     true),  // NIST K-571
-        T571_R1(14, "sect571r1",    "1.3.132.0.39",     true),  // NIST B-571
-
-        P160_K1(15, "secp160k1",    "1.3.132.0.9",      false),
-        P160_R1(16, "secp160r1",    "1.3.132.0.8",      false),
-        P160_R2(17, "secp160r2",    "1.3.132.0.30",     false),
-        P192_K1(18, "secp192k1",    "1.3.132.0.31",     false),
-        P192_R1(19, "secp192r1",    "1.2.840.10045.3.1.1", true), // NIST P-192
-        P224_K1(20, "secp224k1",    "1.3.132.0.32",     false),
-        P224_R1(21, "secp224r1",    "1.3.132.0.33",     true),  // NIST P-224
-        P256_K1(22, "secp256k1",    "1.3.132.0.10",     false),
-        P256_R1(23, "secp256r1",    "1.2.840.10045.3.1.7", true), // NIST P-256
-        P384_R1(24, "secp384r1",    "1.3.132.0.34",     true),  // NIST P-384
-        P521_R1(25, "secp521r1",    "1.3.132.0.35",     true);  // NIST P-521
-
-        int          id;
-        String       name;
-        String       oid;
-        boolean      isFips;
-
-        NamedEllipticCurve(int id, String name, String oid, boolean isFips) {
-            this.id = id;
-            this.name = name;
-            this.oid = oid;
-            this.isFips = isFips;
-
-            if (oidToIdMap.put(oid, id) != null ||
-                idToOidMap.put(id, oid) != null) {
-
-                throw new RuntimeException(
-                        "Duplicate named elliptic curve definition: " + name);
-            }
-        }
-
-        static NamedEllipticCurve getCurve(String name, boolean requireFips) {
-            for (NamedEllipticCurve curve : NamedEllipticCurve.values()) {
-                if (curve.name.equals(name) && (!requireFips || curve.isFips)) {
-                    return curve;
-                }
-            }
-
-            return null;
-        }
-    }
-
-    static {
-        boolean requireFips = SunJSSE.isFIPS();
-
-        // hack code to initialize NamedEllipticCurve
-        NamedEllipticCurve nec =
-                NamedEllipticCurve.getCurve("secp256r1", false);
-
-        // The value of the System Property defines a list of enabled named
-        // curves in preference order, separated with comma.  For example:
-        //
-        //      jdk.tls.namedGroups="secp521r1, secp256r1, secp384r1"
-        //
-        // If the System Property is not defined or the value is empty, the
-        // default curves and preferences will be used.
-        String property = AccessController.doPrivileged(
-                    new GetPropertyAction("jdk.tls.namedGroups"));
-        if (property != null && property.length() != 0) {
-            // remove double quote marks from beginning/end of the property
-            if (property.length() > 1 && property.charAt(0) == '"' &&
-                    property.charAt(property.length() - 1) == '"') {
-                property = property.substring(1, property.length() - 1);
-            }
-        }
-
-        ArrayList<Integer> idList;
-        if (property != null && property.length() != 0) {   // customized curves
-            String[] curves = property.split(",");
-            idList = new ArrayList<>(curves.length);
-            for (String curve : curves) {
-                curve = curve.trim();
-                if (!curve.isEmpty()) {
-                    NamedEllipticCurve namedCurve =
-                            NamedEllipticCurve.getCurve(curve, requireFips);
-                    if (namedCurve != null) {
-                        if (isAvailableCurve(namedCurve.id)) {
-                            idList.add(namedCurve.id);
-                        }
-                    }   // ignore unknown curves
-                }
-            }
-            if (idList.isEmpty() && JsseJce.isEcAvailable()) {
-                throw new IllegalArgumentException(
-                    "System property jdk.tls.namedGroups(" + property + ") " +
-                    "contains no supported elliptic curves");
-            }
-        } else {        // default curves
-            int[] ids;
-            if (requireFips) {
-                ids = new int[] {
-                    // only NIST curves in FIPS mode
-                    23, 24, 25, 9, 10, 11, 12, 13, 14,
-                };
-            } else {
-                ids = new int[] {
-                    // NIST curves first
-                    23, 24, 25, 9, 10, 11, 12, 13, 14,
-                    // non-NIST curves
-                    22,
-                };
-            }
-
-            idList = new ArrayList<>(ids.length);
-            for (int curveId : ids) {
-                if (isAvailableCurve(curveId)) {
-                    idList.add(curveId);
-                }
-            }
-        }
-
-        if (debug != null && idList.isEmpty()) {
-            debug.println(
-                "Initialized [jdk.tls.namedGroups|default] list contains " +
-                "no available elliptic curves. " +
-                (property != null ? "(" + property + ")" : "[Default]"));
-        }
-
-            supportedCurveIds = new int[idList.size()];
-            int i = 0;
-            for (Integer id : idList) {
-                supportedCurveIds[i++] = id;
-            }
-        }
-
-    // check whether the curve is supported by the underlying providers
-    private static boolean isAvailableCurve(int curveId) {
-        String oid = idToOidMap.get(curveId);
-        if (oid != null) {
-            AlgorithmParameters params = null;
-            try {
-                params = JsseJce.getAlgorithmParameters("EC");
-                params.init(new ECGenParameterSpec(oid));
-            } catch (Exception e) {
-                return false;
-            }
-
-            // cache the parameters
-            idToParams.put(curveId, params);
-
-            return true;
-        }
-
-        return false;
-    }
-
-    private SupportedEllipticCurvesExtension(int[] curveIds) {
-        super(ExtensionType.EXT_ELLIPTIC_CURVES);
-        this.curveIds = curveIds;
-    }
-
-    SupportedEllipticCurvesExtension(HandshakeInStream s, int len)
-            throws IOException {
-        super(ExtensionType.EXT_ELLIPTIC_CURVES);
-        int k = s.getInt16();
-        if (((len & 1) != 0) || (k + 2 != len)) {
-            throw new SSLProtocolException("Invalid " + type + " extension");
-        }
-
-        // Note: unknown curves will be ignored later.
-        curveIds = new int[k >> 1];
-        for (int i = 0; i < curveIds.length; i++) {
-            curveIds[i] = s.getInt16();
-        }
-    }
-
-    // get the preferred active curve
-    static int getActiveCurves(AlgorithmConstraints constraints) {
-        return getPreferredCurve(supportedCurveIds, constraints);
-    }
-
-    static boolean hasActiveCurves(AlgorithmConstraints constraints) {
-        return getActiveCurves(constraints) >= 0;
-    }
-
-    static SupportedEllipticCurvesExtension createExtension(
-                AlgorithmConstraints constraints) {
-
-        ArrayList<Integer> idList = new ArrayList<>(supportedCurveIds.length);
-        for (int curveId : supportedCurveIds) {
-            if (constraints.permits(
-                    EnumSet.of(CryptoPrimitive.KEY_AGREEMENT),
-                                "EC", idToParams.get(curveId))) {
-                idList.add(curveId);
-            }
-        }
-
-        if (!idList.isEmpty()) {
-            int[] ids = new int[idList.size()];
-            int i = 0;
-            for (Integer id : idList) {
-                ids[i++] = id;
-            }
-
-            return new SupportedEllipticCurvesExtension(ids);
-        }
-
-        return null;
-    }
-
-    // get the preferred activated curve
-    int getPreferredCurve(AlgorithmConstraints constraints) {
-        return getPreferredCurve(curveIds, constraints);
-    }
-
-    // get a preferred activated curve
-    private static int getPreferredCurve(int[] curves,
-                AlgorithmConstraints constraints) {
-        for (int curveId : curves) {
-            if (isSupported(curveId) && constraints.permits(
-                    EnumSet.of(CryptoPrimitive.KEY_AGREEMENT),
-                                "EC", idToParams.get(curveId))) {
-                return curveId;
-            }
-        }
-
-        return -1;
-    }
-
-    boolean contains(int index) {
-        for (int curveId : curveIds) {
-            if (index == curveId) {
-                return true;
-            }
-        }
-        return false;
-    }
-
-    @Override
-    int length() {
-        return 6 + (curveIds.length << 1);
-    }
-
-    @Override
-    void send(HandshakeOutStream s) throws IOException {
-        s.putInt16(type.id);
-        int k = curveIds.length << 1;
-        s.putInt16(k + 2);
-        s.putInt16(k);
-        for (int curveId : curveIds) {
-            s.putInt16(curveId);
-        }
-    }
-
-    @Override
-    public String toString() {
-        StringBuilder sb = new StringBuilder();
-        sb.append("Extension " + type + ", curve names: {");
-        boolean first = true;
-        for (int curveId : curveIds) {
-            if (first) {
-                first = false;
-            } else {
-                sb.append(", ");
-            }
-            String curveName = getCurveName(curveId);
-            if (curveName != null) {
-                sb.append(curveName);
-            } else if (curveId == ARBITRARY_PRIME) {
-                sb.append("arbitrary_explicit_prime_curves");
-            } else if (curveId == ARBITRARY_CHAR2) {
-                sb.append("arbitrary_explicit_char2_curves");
-            } else {
-                sb.append("unknown curve " + curveId);
-            }
-        }
-        sb.append("}");
-        return sb.toString();
-    }
-
-    // Test whether the given curve is supported.
-    static boolean isSupported(int index) {
-        for (int curveId : supportedCurveIds) {
-            if (index == curveId) {
-                return true;
-            }
-        }
-
-        return false;
-    }
-
-    static int getCurveIndex(ECParameterSpec params) {
-        String oid = JsseJce.getNamedCurveOid(params);
-        if (oid == null) {
-            return -1;
-        }
-        Integer n = oidToIdMap.get(oid);
-        return (n == null) ? -1 : n;
-    }
-
-    static String getCurveOid(int index) {
-        return idToOidMap.get(index);
-    }
-
-    static ECGenParameterSpec getECGenParamSpec(int index) {
-        AlgorithmParameters params = idToParams.get(index);
-        try {
-            return params.getParameterSpec(ECGenParameterSpec.class);
-        } catch (InvalidParameterSpecException ipse) {
-            // should be unlikely
-            String curveOid = getCurveOid(index);
-            return new ECGenParameterSpec(curveOid);
-        }
-    }
-
-    private static String getCurveName(int index) {
-        for (NamedEllipticCurve namedCurve : NamedEllipticCurve.values()) {
-            if (namedCurve.id == index) {
-                return namedCurve.name;
-            }
-        }
-
-        return null;
-    }
-}
--- a/src/share/classes/sun/security/ssl/SupportedEllipticPointFormatsExtension.java	Mon Jan 08 22:36:23 2018 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,104 +0,0 @@
-/*
- * Copyright (c) 2006, 2012, 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.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * 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.
- */
-
-package sun.security.ssl;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.net.ssl.SSLProtocolException;
-
-final class SupportedEllipticPointFormatsExtension extends HelloExtension {
-
-    final static int FMT_UNCOMPRESSED = 0;
-    final static int FMT_ANSIX962_COMPRESSED_PRIME = 1;
-    final static int FMT_ANSIX962_COMPRESSED_CHAR2 = 2;
-
-    static final HelloExtension DEFAULT =
-        new SupportedEllipticPointFormatsExtension(
-            new byte[] {FMT_UNCOMPRESSED});
-
-    private final byte[] formats;
-
-    private SupportedEllipticPointFormatsExtension(byte[] formats) {
-        super(ExtensionType.EXT_EC_POINT_FORMATS);
-        this.formats = formats;
-    }
-
-    SupportedEllipticPointFormatsExtension(HandshakeInStream s, int len)
-            throws IOException {
-        super(ExtensionType.EXT_EC_POINT_FORMATS);
-        formats = s.getBytes8();
-        // RFC 4492 says uncompressed points must always be supported.
-        // Check just to make sure.
-        boolean uncompressed = false;
-        for (int format : formats) {
-            if (format == FMT_UNCOMPRESSED) {
-                uncompressed = true;
-                break;
-            }
-        }
-        if (uncompressed == false) {
-            throw new SSLProtocolException
-                ("Peer does not support uncompressed points");
-        }
-    }
-
-    @Override
-    int length() {
-        return 5 + formats.length;
-    }
-
-    @Override
-    void send(HandshakeOutStream s) throws IOException {
-        s.putInt16(type.id);
-        s.putInt16(formats.length + 1);
-        s.putBytes8(formats);
-    }
-
-    private static String toString(byte format) {
-        int f = format & 0xff;
-        switch (f) {
-        case FMT_UNCOMPRESSED:
-            return "uncompressed";
-        case FMT_ANSIX962_COMPRESSED_PRIME:
-            return "ansiX962_compressed_prime";
-        case FMT_ANSIX962_COMPRESSED_CHAR2:
-            return "ansiX962_compressed_char2";
-        default:
-            return "unknown-" + f;
-        }
-    }
-
-    @Override
-    public String toString() {
-        List<String> list = new ArrayList<String>();
-        for (byte format : formats) {
-            list.add(toString(format));
-        }
-        return "Extension " + type + ", formats: " + list;
-    }
-}
--- a/src/share/classes/sun/security/tools/keytool/Main.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/security/tools/keytool/Main.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1704,11 +1704,9 @@
             if ("EC".equalsIgnoreCase(keyAlgName)) {
                 keysize = SecurityProviderConstants.DEF_EC_KEY_SIZE;
             } else if ("RSA".equalsIgnoreCase(keyAlgName)) {
-                // hardcode for now as DEF_RSA_KEY_SIZE is still 1024
-                keysize = 2048; // SecurityProviderConstants.DEF_RSA_KEY_SIZE;
+                keysize = SecurityProviderConstants.DEF_RSA_KEY_SIZE;
             } else if ("DSA".equalsIgnoreCase(keyAlgName)) {
-                // hardcode for now as DEF_DSA_KEY_SIZE is still 1024
-                keysize = 2048;
+                keysize = SecurityProviderConstants.DEF_DSA_KEY_SIZE;
             }
         }
 
--- a/src/share/classes/sun/security/tools/keytool/Resources.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/security/tools/keytool/Resources.java	Tue Jan 16 22:58:44 2018 -0800
@@ -439,20 +439,20 @@
         {"the.tsa.certificate", "The TSA certificate"},
         {"the.input", "The input"},
         {"reply", "Reply"},
-        {"one.in.many", "%s #%d of %d"},
+        {"one.in.many", "%1$s #%2$d of %3$d"},
         {"alias.in.cacerts", "Issuer <%s> in cacerts"},
         {"alias.in.keystore", "Issuer <%s>"},
         {"with.weak", "%s (weak)"},
-        {"key.bit", "%d-bit %s key"},
-        {"key.bit.weak", "%d-bit %s key (weak)"},
+        {"key.bit", "%1$d-bit %2$s key"},
+        {"key.bit.weak", "%1$d-bit %2$s key (weak)"},
         {".PATTERN.printX509Cert.with.weak",
                 "Owner: {0}\nIssuer: {1}\nSerial number: {2}\nValid from: {3} until: {4}\nCertificate fingerprints:\n\t MD5:  {5}\n\t SHA1: {6}\n\t SHA256: {7}\nSignature algorithm name: {8}\nSubject Public Key Algorithm: {9}\nVersion: {10}"},
         {"PKCS.10.with.weak",
                 "PKCS #10 Certificate Request (Version 1.0)\n" +
-                        "Subject: %s\nFormat: %s\nPublic Key: %s\nSignature algorithm: %s\n"},
-        {"verified.by.s.in.s.weak", "Verified by %s in %s with a %s"},
-        {"whose.sigalg.risk", "%s uses the %s signature algorithm which is considered a security risk."},
-        {"whose.key.risk", "%s uses a %s which is considered a security risk."},
+                        "Subject: %1$s\nFormat: %2$s\nPublic Key: %3$s\nSignature algorithm: %4$s\n"},
+        {"verified.by.s.in.s.weak", "Verified by %1$s in %2$s with a %3$s"},
+        {"whose.sigalg.risk", "%1$s uses the %2$s signature algorithm which is considered a security risk."},
+        {"whose.key.risk", "%1$s uses a %2$s which is considered a security risk."},
         {"jks.storetype.warning", "The %1$s keystore uses a proprietary format. It is recommended to migrate to PKCS12 which is an industry standard format using \"keytool -importkeystore -srckeystore %2$s -destkeystore %2$s -deststoretype pkcs12\"."},
         {"migrate.keystore.warning", "Migrated \"%1$s\" to %4$s. The %2$s keystore is backed up as \"%3$s\"."},
         {"backup.keystore.warning", "The original keystore \"%1$s\" is backed up as \"%3$s\"..."},
--- a/src/share/classes/sun/security/tools/keytool/Resources_de.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/security/tools/keytool/Resources_de.java	Tue Jan 16 22:58:44 2018 -0800
@@ -435,19 +435,19 @@
         {"the.tsa.certificate", "Das TSA-Zertifikat"},
         {"the.input", "Die Eingabe"},
         {"reply", "Antwort"},
-        {"one.in.many", "%s #%d von %d"},
+        {"one.in.many", "%1$s #%2$d von %3$d"},
         {"alias.in.cacerts", "Aussteller <%s> in cacerts"},
         {"alias.in.keystore", "Aussteller <%s>"},
         {"with.weak", "%s (schwach)"},
-        {"key.bit", "%d-Bit-%s-Schl\u00FCssel"},
-        {"key.bit.weak", "%d-Bit-%s-Schl\u00FCssel (schwach)"},
+        {"key.bit", "%1$d-Bit-%2$s-Schl\u00FCssel"},
+        {"key.bit.weak", "%1$d-Bit-%2$s-Schl\u00FCssel (schwach)"},
         {".PATTERN.printX509Cert.with.weak",
                 "Eigent\u00FCmer: {0}\nAussteller: {1}\nSeriennummer: {2}\nG\u00FCltig von: {3} bis: {4}\nZertifikatfingerprints:\n\t MD5: {5}\n\t SHA1: {6}\n\t SHA256: {7}\nSignaturalgorithmusname: {8}\nAlgorithmus des Public Key von Betreff: {9}\nVersion: {10}"},
         {"PKCS.10.with.weak",
-                "PKCS #10-Zertifikatsanforderung (Version 1.0)\nSubject: %s\nFormat: %s\nPublic Key: %s\nSignaturalgorithmus: %s\n"},
-        {"verified.by.s.in.s.weak", "Von %s in %s mit %s verifiziert"},
-        {"whose.sigalg.risk", "%s verwendet den Signaturalgorithmus %s. Dies gilt als Sicherheitsrisiko."},
-        {"whose.key.risk", "%s verwendet %s. Dies gilt als Sicherheitsrisiko."},
+                "PKCS #10-Zertifikatsanforderung (Version 1.0)\nSubject: %1$s\nFormat: %2$s\nPublic Key: %3$s\nSignaturalgorithmus: %4$s\n"},
+        {"verified.by.s.in.s.weak", "Von %1$s in %2$s mit %3$s verifiziert"},
+        {"whose.sigalg.risk", "%1$s verwendet den Signaturalgorithmus %2$s. Dies gilt als Sicherheitsrisiko."},
+        {"whose.key.risk", "%1$s verwendet %2$s. Dies gilt als Sicherheitsrisiko."},
         {"jks.storetype.warning", "Der %1$s-Keystore verwendet ein propriet\u00E4res Format. Es wird empfohlen, auf PKCS12 zu migrieren, das ein Industriestandardformat mit \"keytool -importkeystore -srckeystore %2$s -destkeystore %2$s -deststoretype pkcs12\" ist."},
         {"migrate.keystore.warning", "\"%1$s\" zu %4$s migriert. Der %2$s-Keystore wurde als \"%3$s\" gesichert."},
         {"backup.keystore.warning", "Der urspr\u00FCngliche Keystore \"%1$s\" wird als \"%3$s\" gesichert..."},
--- a/src/share/classes/sun/security/tools/keytool/Resources_es.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/security/tools/keytool/Resources_es.java	Tue Jan 16 22:58:44 2018 -0800
@@ -435,19 +435,19 @@
         {"the.tsa.certificate", "El certificado de TSA"},
         {"the.input", "La entrada"},
         {"reply", "Responder"},
-        {"one.in.many", "%s #%d de %d"},
+        {"one.in.many", "%1$s #%2$d de %3$d"},
         {"alias.in.cacerts", "Emisor <%s> en cacerts"},
         {"alias.in.keystore", "Emisor <%s>"},
         {"with.weak", "%s (d\u00E9bil)"},
-        {"key.bit", "Clave %s de %d bits"},
-        {"key.bit.weak", "Clave %s de %d bits (d\u00E9bil)"},
+        {"key.bit", "Clave %2$s de %1$d bits"},
+        {"key.bit.weak", "Clave %2$s de %1$d bits (d\u00E9bil)"},
         {".PATTERN.printX509Cert.with.weak",
                 "Propietario: {0}\nEmisor: {1}\nN\u00FAmero de serie: {2}\nV\u00E1lido desde: {3} hasta: {4}\nHuellas digitales del certificado:\n\t MD5: {5}\n\t SHA1: {6}\n\t SHA256: {7}\nNombre del algoritmo de firma: {8}\nAlgoritmo de clave p\u00FAblica de asunto: {9}\nVersi\u00F3n: {10}"},
         {"PKCS.10.with.weak",
-                "Solicitud de certificado PKCS #10 (Versi\u00F3n 1.0)\nAsunto: %s\nFormato: %s\nClave p\u00FAblica:%s\nAlgoritmo de firma: %s\n"},
-        {"verified.by.s.in.s.weak", "Verificado por %s en %s con %s"},
-        {"whose.sigalg.risk", "%s usa el algoritmo de firma %s, lo que se considera un riesgo de seguridad."},
-        {"whose.key.risk", "%s usa %s, lo que se considera un riesgo de seguridad."},
+                "Solicitud de certificado PKCS #10 (Versi\u00F3n 1.0)\nAsunto: %1$s\nFormato: %2$s\nClave p\u00FAblica: %3$s\nAlgoritmo de firma: %4$s\n"},
+        {"verified.by.s.in.s.weak", "Verificado por %1$s en %2$s con %3$s"},
+        {"whose.sigalg.risk", "%1$s utiliza el algoritmo de firma %2$s, lo que se considera un riesgo de seguridad."},
+        {"whose.key.risk", "%1$s utiliza %2$s, lo que se considera riesgo de seguridad."},
         {"jks.storetype.warning", "El almac\u00E9n de claves %1$s utiliza un formato propietario. Se recomienda migrar a PKCS12, que es un formato est\u00E1ndar del sector que utiliza \"keytool -importkeystore -srckeystore %2$s -destkeystore %2$s -deststoretype pkcs12\"."},
         {"migrate.keystore.warning", "Se ha migrado \"%1$s\" a %4$s. Se ha realizado la copia de seguridad del almac\u00E9n de claves %2$s como \"%3$s\"."},
         {"backup.keystore.warning", "La copia de seguridad del almac\u00E9n de claves \"%1$s\" se ha realizado como \"%3$s\"..."},
--- a/src/share/classes/sun/security/tools/keytool/Resources_fr.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/security/tools/keytool/Resources_fr.java	Tue Jan 16 22:58:44 2018 -0800
@@ -435,19 +435,19 @@
         {"the.tsa.certificate", "Certificat TSA"},
         {"the.input", "Entr\u00E9e"},
         {"reply", "R\u00E9pondre"},
-        {"one.in.many", "%s #%d sur %d"},
+        {"one.in.many", "%1$s #%2$d sur %3$d"},
         {"alias.in.cacerts", "Emetteur <%s> dans les certificats CA"},
         {"alias.in.keystore", "Emetteur <%s>"},
         {"with.weak", "%s (faible)"},
-        {"key.bit", "Cl\u00E9 %s %d bits"},
-        {"key.bit.weak", "Cl\u00E9 %s %d bits (faible)"},
+        {"key.bit", "Cl\u00E9 %2$s %1$d bits"},
+        {"key.bit.weak", "Cl\u00E9 %2$s %1$d bits (faible)"},
         {".PATTERN.printX509Cert.with.weak",
                 "Propri\u00E9taire : {0}\nEmetteur : {1}\nNum\u00E9ro de s\u00E9rie : {2}\nValide du : {3} au : {4}\nEmpreintes du certificat :\n\t MD5 : {5}\n\t SHA1 : {6}\n\t SHA256 : {7}\nNom de l''algorithme de signature : {8}\nAlgorithme de cl\u00E9 publique du sujet : {9}\nVersion : {10}"},
         {"PKCS.10.with.weak",
-                "Demande de certificat PKCS #10 (version 1.0)\nSujet : %s\nFormat : %s\nCl\u00E9 publique : %s\nAlgorithme de signature : %s\n"},
-        {"verified.by.s.in.s.weak", "V\u00E9rifi\u00E9 par %s dans %s avec un \u00E9l\u00E9ment %s"},
-        {"whose.sigalg.risk", "%s utilise l'algorithme de signature %s, qui repr\u00E9sente un risque pour la s\u00E9curit\u00E9."},
-        {"whose.key.risk", "%s utilise un \u00E9l\u00E9ment %s, qui repr\u00E9sente un risque pour la s\u00E9curit\u00E9."},
+                "Demande de certificat PKCS #10 (version 1.0)\nSujet : %1$s\nFormat : %2$s\nCl\u00E9 publique : %3$s\nAlgorithme de signature : %4$s\n"},
+        {"verified.by.s.in.s.weak", "V\u00E9rifi\u00E9 par %1$s dans %2$s avec un \u00E9l\u00E9ment %3$s"},
+        {"whose.sigalg.risk", "%1$s utilise l'algorithme de signature %2$s, qui repr\u00E9sente un risque pour la s\u00E9curit\u00E9."},
+        {"whose.key.risk", "%1$s utilise un \u00E9l\u00E9ment %2$s, qui repr\u00E9sente un risque pour la s\u00E9curit\u00E9."},
         {"jks.storetype.warning", "Le fichier de cl\u00E9s %1$s utilise un format propri\u00E9taire. Il est recommand\u00E9 de migrer vers PKCS12, qui est un format standard de l'industrie en utilisant \"keytool -importkeystore -srckeystore %2$s -destkeystore %2$s -deststoretype pkcs12\"."},
         {"migrate.keystore.warning", "El\u00E9ment \"%1$s\" migr\u00E9 vers %4$s. Le fichier de cl\u00E9s %2$s est sauvegard\u00E9 en tant que \"%3$s\"."},
         {"backup.keystore.warning", "Le fichier de cl\u00E9s d'origine \"%1$s\" est sauvegard\u00E9 en tant que \"%3$s\"..."},
--- a/src/share/classes/sun/security/tools/keytool/Resources_it.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/security/tools/keytool/Resources_it.java	Tue Jan 16 22:58:44 2018 -0800
@@ -435,19 +435,19 @@
         {"the.tsa.certificate", "Il certificato TSA"},
         {"the.input", "L'input"},
         {"reply", "Rispondi"},
-        {"one.in.many", "%s #%d di %d"},
+        {"one.in.many", "%1$s #%2$d di %3$d"},
         {"alias.in.cacerts", "Emittente <%s> in cacerts"},
         {"alias.in.keystore", "Emittente <%s>"},
         {"with.weak", "%s (debole)"},
-        {"key.bit", "Chiave %s a %d bit"},
-        {"key.bit.weak", "Chiave %s a %d bit (debole)"},
+        {"key.bit", "Chiave %2$s a %1$d bit"},
+        {"key.bit.weak", "Chiave %2$s a %1$d bit (debole)"},
         {".PATTERN.printX509Cert.with.weak",
                 "Proprietario: {0}\nEmittente: {1}\nNumero di serie: {2}\nValido da: {3} a: {4}\nImpronte certificato:\n\t MD5:  {5}\n\t SHA1: {6}\n\t SHA256: {7}\nNome algoritmo firma: {8}\nAlgoritmo di chiave pubblica oggetto: {9}\nVersione: {10}"},
         {"PKCS.10.with.weak",
-                "Richiesta di certificato PKCS #10 (versione 1.0)\nOggetto: %s\nFormato: %s\nChiave pubblica: %s\nAlgoritmo firma: %s\n"},
-        {"verified.by.s.in.s.weak", "Verificato da %s in %s con un %s"},
-        {"whose.sigalg.risk", "%s utilizza l'algoritmo firma %s che \u00E8 considerato un rischio per la sicurezza."},
-        {"whose.key.risk", "%s utilizza un %s che \u00E8 considerato un rischio per la sicurezza."},
+                "Richiesta di certificato PKCS #10 (versione 1.0)\nOggetto: %1$s\nFormato: %2$s\nChiave pubblica: %3$s\nAlgoritmo firma: %4$s\n"},
+        {"verified.by.s.in.s.weak", "Verificato da %1$s in %2$s con un %3$s"},
+        {"whose.sigalg.risk", "%1$s utilizza l'algoritmo firma %2$s che \u00E8 considerato un rischio per la sicurezza."},
+        {"whose.key.risk", "%1$s utilizza un %2$s che \u00E8 considerato un rischio per la sicurezza."},
         {"jks.storetype.warning", "Il keystore %1$s utilizza un formato proprietario. Si consiglia di eseguire la migrazione a PKCS12, un formato standard di settore, utilizzando il comando \"keytool -importkeystore -srckeystore %2$s -destkeystore %2$s -deststoretype pkcs12\"."},
         {"migrate.keystore.warning", "Migrazione di \"%1$s\" in %4$s eseguita. Backup del keystore %2$s eseguito con il nome \"%3$s\"."},
         {"backup.keystore.warning", "Backup del keystore originale \"%1$s\" eseguito con il nome \"%3$s\"..."},
--- a/src/share/classes/sun/security/tools/keytool/Resources_ja.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/security/tools/keytool/Resources_ja.java	Tue Jan 16 22:58:44 2018 -0800
@@ -435,19 +435,19 @@
         {"the.tsa.certificate", "TSA\u8A3C\u660E\u66F8"},
         {"the.input", "\u5165\u529B"},
         {"reply", "\u5FDC\u7B54"},
-        {"one.in.many", "%s #%d / %d"},
+        {"one.in.many", "%1$s #%2$d / %3$d"},
         {"alias.in.cacerts", "cacerts\u5185\u306E\u767A\u884C\u8005<%s>"},
         {"alias.in.keystore", "\u767A\u884C\u8005<%s>"},
         {"with.weak", "%s (\u5F31)"},
-        {"key.bit", "%d\u30D3\u30C3\u30C8%s\u9375"},
-        {"key.bit.weak", "%d\u30D3\u30C3\u30C8%s\u9375(\u5F31)"},
+        {"key.bit", "%1$d\u30D3\u30C3\u30C8%2$s\u9375"},
+        {"key.bit.weak", "%1$d\u30D3\u30C3\u30C8%2$s\u9375(\u5F31)"},
         {".PATTERN.printX509Cert.with.weak",
                 "\u6240\u6709\u8005: {0}\n\u767A\u884C\u8005: {1}\n\u30B7\u30EA\u30A2\u30EB\u756A\u53F7: {2}\n\u6709\u52B9\u671F\u9593\u306E\u958B\u59CB\u65E5: {3} \u7D42\u4E86\u65E5: {4}\n\u8A3C\u660E\u66F8\u306E\u30D5\u30A3\u30F3\u30AC\u30D7\u30EA\u30F3\u30C8:\n\t MD5:  {5}\n\t SHA1: {6}\n\t SHA256: {7}\n\u7F72\u540D\u30A2\u30EB\u30B4\u30EA\u30BA\u30E0\u540D: {8}\n\u30B5\u30D6\u30B8\u30A7\u30AF\u30C8\u516C\u958B\u9375\u30A2\u30EB\u30B4\u30EA\u30BA\u30E0: {9}\n\u30D0\u30FC\u30B8\u30E7\u30F3: {10}"},
         {"PKCS.10.with.weak",
-                "PKCS #10\u8A3C\u660E\u66F8\u30EA\u30AF\u30A8\u30B9\u30C8(\u30D0\u30FC\u30B8\u30E7\u30F31.0)\n\u30B5\u30D6\u30B8\u30A7\u30AF\u30C8: %s\n\u30D5\u30A9\u30FC\u30DE\u30C3\u30C8 %s\n\u516C\u958B\u9375: %s\n\u7F72\u540D\u30A2\u30EB\u30B4\u30EA\u30BA\u30E0: %s\n"},
-        {"verified.by.s.in.s.weak", "%s(%s\u5185)\u306B\u3088\u308A%s\u3067\u691C\u8A3C\u3055\u308C\u307E\u3057\u305F"},
-        {"whose.sigalg.risk", "%s\u306F\u30BB\u30AD\u30E5\u30EA\u30C6\u30A3\u30FB\u30EA\u30B9\u30AF\u3068\u307F\u306A\u3055\u308C\u308B%s\u7F72\u540D\u30A2\u30EB\u30B4\u30EA\u30BA\u30E0\u3092\u4F7F\u7528\u3057\u3066\u3044\u307E\u3059\u3002"},
-        {"whose.key.risk", "%s\u306F\u30BB\u30AD\u30E5\u30EA\u30C6\u30A3\u30FB\u30EA\u30B9\u30AF\u3068\u307F\u306A\u3055\u308C\u308B%s\u3092\u4F7F\u7528\u3057\u3066\u3044\u307E\u3059\u3002"},
+                "PKCS #10\u8A3C\u660E\u66F8\u30EA\u30AF\u30A8\u30B9\u30C8(\u30D0\u30FC\u30B8\u30E7\u30F31.0)\n\u30B5\u30D6\u30B8\u30A7\u30AF\u30C8: %1$s\n\u30D5\u30A9\u30FC\u30DE\u30C3\u30C8: %2$s\n\u516C\u958B\u9375: %3$s\n\u7F72\u540D\u30A2\u30EB\u30B4\u30EA\u30BA\u30E0: %4$s\n"},
+        {"verified.by.s.in.s.weak", "%2$s\u5185\u306E%1$s\u306B\u3088\u308A%3$s\u3067\u691C\u8A3C\u3055\u308C\u307E\u3057\u305F"},
+        {"whose.sigalg.risk", "%1$s\u306F%2$s\u7F72\u540D\u30A2\u30EB\u30B4\u30EA\u30BA\u30E0\u3092\u4F7F\u7528\u3057\u3066\u304A\u308A\u3001\u3053\u308C\u306F\u30BB\u30AD\u30E5\u30EA\u30C6\u30A3\u30FB\u30EA\u30B9\u30AF\u3068\u307F\u306A\u3055\u308C\u307E\u3059\u3002"},
+        {"whose.key.risk", "%1$s\u306F%2$s\u3092\u4F7F\u7528\u3057\u3066\u304A\u308A\u3001\u3053\u308C\u306F\u30BB\u30AD\u30E5\u30EA\u30C6\u30A3\u30FB\u30EA\u30B9\u30AF\u3068\u307F\u306A\u3055\u308C\u307E\u3059\u3002"},
         {"jks.storetype.warning", "%1$s\u30AD\u30FC\u30B9\u30C8\u30A2\u306F\u72EC\u81EA\u306E\u5F62\u5F0F\u3092\u4F7F\u7528\u3057\u3066\u3044\u307E\u3059\u3002\"keytool -importkeystore -srckeystore %2$s -destkeystore %2$s -deststoretype pkcs12\"\u3092\u4F7F\u7528\u3059\u308B\u696D\u754C\u6A19\u6E96\u306E\u5F62\u5F0F\u3067\u3042\u308BPKCS12\u306B\u79FB\u884C\u3059\u308B\u3053\u3068\u3092\u304A\u85A6\u3081\u3057\u307E\u3059\u3002"},
         {"migrate.keystore.warning", "\"%1$s\"\u304C%4$s\u306B\u79FB\u884C\u3055\u308C\u307E\u3057\u305F\u3002%2$s\u30AD\u30FC\u30B9\u30C8\u30A2\u306F\"%3$s\"\u3068\u3057\u3066\u30D0\u30C3\u30AF\u30A2\u30C3\u30D7\u3055\u308C\u307E\u3059\u3002"},
         {"backup.keystore.warning", "\u5143\u306E\u30AD\u30FC\u30B9\u30C8\u30A2\"%1$s\"\u306F\"%3$s\"\u3068\u3057\u3066\u30D0\u30C3\u30AF\u30A2\u30C3\u30D7\u3055\u308C\u307E\u3059..."},
--- a/src/share/classes/sun/security/tools/keytool/Resources_ko.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/security/tools/keytool/Resources_ko.java	Tue Jan 16 22:58:44 2018 -0800
@@ -435,19 +435,19 @@
         {"the.tsa.certificate", "TSA \uC778\uC99D\uC11C"},
         {"the.input", "\uC785\uB825"},
         {"reply", "\uD68C\uC2E0"},
-        {"one.in.many", "%s #%d/%d"},
+        {"one.in.many", "%1$s #%2$d/%3$d"},
         {"alias.in.cacerts", "cacerts\uC758 <%s> \uBC1C\uD589\uC790"},
         {"alias.in.keystore", "<%s> \uBC1C\uD589\uC790"},
         {"with.weak", "%s(\uC57D\uD568)"},
-        {"key.bit", "%d\uBE44\uD2B8 %s \uD0A4"},
-        {"key.bit.weak", "%d\uBE44\uD2B8 %s \uD0A4(\uC57D\uD568)"},
+        {"key.bit", "%1$d\uBE44\uD2B8 %2$s \uD0A4"},
+        {"key.bit.weak", "%1$d\uBE44\uD2B8 %2$s \uD0A4(\uC57D\uD568)"},
         {".PATTERN.printX509Cert.with.weak",
                 "\uC18C\uC720\uC790: {0}\n\uBC1C\uD589\uC790: {1}\n\uC77C\uB828 \uBC88\uD638: {2}\n\uC801\uD569\uD55C \uC2DC\uC791 \uB0A0\uC9DC: {3} \uC885\uB8CC \uB0A0\uC9DC: {4}\n\uC778\uC99D\uC11C \uC9C0\uBB38:\n\t MD5:  {5}\n\t SHA1: {6}\n\t SHA256: {7}\n\uC11C\uBA85 \uC54C\uACE0\uB9AC\uC998 \uC774\uB984: {8}\n\uC8FC\uCCB4 \uACF5\uC6A9 \uD0A4 \uC54C\uACE0\uB9AC\uC998: {9}\n\uBC84\uC804: {10}"},
         {"PKCS.10.with.weak",
-                "PKCS #10 \uC778\uC99D\uC11C \uC694\uCCAD(1.0 \uBC84\uC804)\n\uC81C\uBAA9: %s\n\uD615\uC2DD: %s\n\uACF5\uC6A9 \uD0A4: %s\n\uC11C\uBA85 \uC54C\uACE0\uB9AC\uC998: %s\n"},
-        {"verified.by.s.in.s.weak", "%s\uC774(\uAC00) %s\uC5D0\uC11C %s\uC744(\uB97C) \uC0AC\uC6A9\uD558\uC5EC \uD655\uC778"},
-        {"whose.sigalg.risk", "%s\uC774(\uAC00) \uBCF4\uC548 \uC704\uD5D8\uC73C\uB85C \uAC04\uC8FC\uB418\uB294 %s \uC11C\uBA85 \uC54C\uACE0\uB9AC\uC998\uC744 \uC0AC\uC6A9\uD569\uB2C8\uB2E4."},
-        {"whose.key.risk", "%s\uC774(\uAC00) \uBCF4\uC548 \uC704\uD5D8\uC73C\uB85C \uAC04\uC8FC\uB418\uB294 %s\uC744(\uB97C) \uC0AC\uC6A9\uD569\uB2C8\uB2E4."},
+                "PKCS #10 \uC778\uC99D\uC11C \uC694\uCCAD(1.0 \uBC84\uC804)\n\uC81C\uBAA9: %1$s\n\uD615\uC2DD: %2$s\n\uACF5\uC6A9 \uD0A4: %3$s\n\uC11C\uBA85 \uC54C\uACE0\uB9AC\uC998: %4$s\n"},
+        {"verified.by.s.in.s.weak", "%3$s\uC744(\uB97C) \uD3EC\uD568\uD558\uB294 %2$s\uC758 %1$s\uC5D0 \uC758\uD574 \uD655\uC778\uB428"},
+        {"whose.sigalg.risk", "%1$s\uC774(\uAC00) \uBCF4\uC548 \uC704\uD5D8\uC73C\uB85C \uAC04\uC8FC\uB418\uB294 %2$s \uC11C\uBA85 \uC54C\uACE0\uB9AC\uC998\uC744 \uC0AC\uC6A9\uD569\uB2C8\uB2E4."},
+        {"whose.key.risk", "%1$s\uC774(\uAC00) \uBCF4\uC548 \uC704\uD5D8\uC73C\uB85C \uAC04\uC8FC\uB418\uB294 %2$s\uC744(\uB97C) \uC0AC\uC6A9\uD569\uB2C8\uB2E4."},
         {"jks.storetype.warning", "%1$s \uD0A4 \uC800\uC7A5\uC18C\uB294 \uACE0\uC720 \uD615\uC2DD\uC744 \uC0AC\uC6A9\uD569\uB2C8\uB2E4. \"keytool -importkeystore -srckeystore %2$s -destkeystore %2$s -deststoretype pkcs12\"\uB97C \uC0AC\uC6A9\uD558\uB294 \uC0B0\uC5C5 \uD45C\uC900 \uD615\uC2DD\uC778 PKCS12\uB85C \uC774\uC804\uD558\uB294 \uAC83\uC774 \uC88B\uC2B5\uB2C8\uB2E4."},
         {"migrate.keystore.warning", "\"%1$s\"\uC744(\uB97C) %4$s(\uC73C)\uB85C \uC774\uC804\uD588\uC2B5\uB2C8\uB2E4. %2$s \uD0A4 \uC800\uC7A5\uC18C\uAC00 \"%3$s\"(\uC73C)\uB85C \uBC31\uC5C5\uB418\uC5C8\uC2B5\uB2C8\uB2E4."},
         {"backup.keystore.warning", "\uC6D0\uBCF8 \uD0A4 \uC800\uC7A5\uC18C \"%1$s\"\uC774(\uAC00) \"%3$s\"(\uC73C)\uB85C \uBC31\uC5C5\uB418\uC5C8\uC2B5\uB2C8\uB2E4."},
--- a/src/share/classes/sun/security/tools/keytool/Resources_pt_BR.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/security/tools/keytool/Resources_pt_BR.java	Tue Jan 16 22:58:44 2018 -0800
@@ -435,19 +435,19 @@
         {"the.tsa.certificate", "O certificado TSA"},
         {"the.input", "A entrada"},
         {"reply", "Resposta"},
-        {"one.in.many", "%s #%d de %d"},
+        {"one.in.many", "%1$s #%2$d de %3$d"},
         {"alias.in.cacerts", "Emissor <%s> no cacerts"},
         {"alias.in.keystore", "Emissor <%s>"},
         {"with.weak", "%s (fraca)"},
-        {"key.bit", "Chave %s de %d bits"},
-        {"key.bit.weak", "Chave %s de %d bits (fraca)"},
+        {"key.bit", "Chave %2$s de %1$d bits"},
+        {"key.bit.weak", "Chave %2$s de %1$d bits (fraca)"},
         {".PATTERN.printX509Cert.with.weak",
                 "Propriet\u00E1rio: {0}\nEmissor: {1}\nN\u00FAmero de s\u00E9rie: {2}\nV\u00E1lido de {3} at\u00E9 {4}\nFingerprints do certificado:\n\t MD5:  {5}\n\t SHA1: {6}\n\t SHA256: {7}\nNome do algoritmo de assinatura: {8}\nAlgoritmo de Chave P\u00FAblica do Assunto: {9}\nVers\u00E3o: {10}"},
         {"PKCS.10.with.weak",
-                "Solicita\u00E7\u00E3o do Certificado PKCS #10 (Vers\u00E3o 1.0)\nAssunto: %s\nFormato: %s\nChave P\u00FAblica: %s\nAlgoritmo de assinatura: %s\n"},
-        {"verified.by.s.in.s.weak", "Verificado por %s em %s com um %s"},
-        {"whose.sigalg.risk", "%s usa o algoritmo de assinatura %s que \u00E9 considerado um risco \u00E0 seguran\u00E7a."},
-        {"whose.key.risk", "%s usa um %s que \u00E9 considerado um risco \u00E0 seguran\u00E7a."},
+                "Solicita\u00E7\u00E3o do Certificado PKCS #10 (Vers\u00E3o 1.0)\nAssunto: %1$s\nFormato: %2$s\nChave P\u00FAblica: %3$s\nAlgoritmo de assinatura: %4$s\n"},
+        {"verified.by.s.in.s.weak", "Verificado por %1$s em %2$s com um %3$s"},
+        {"whose.sigalg.risk", "%1$s usa o algoritmo de assinatura %2$s que \u00E9 considerado um risco \u00E0 seguran\u00E7a."},
+        {"whose.key.risk", "%1$s usa um %2$s que \u00E9 considerado um risco \u00E0 seguran\u00E7a."},
         {"jks.storetype.warning", "O armazenamento de chaves %1$s usa um formato propriet\u00E1rio. \u00C9 recomendada a migra\u00E7\u00E3o para PKCS12, que \u00E9 um formato de padr\u00E3o industrial que usa \"keytool -importkeystore -srckeystore %2$s -destkeystore %2$s -deststoretype pkcs12\"."},
         {"migrate.keystore.warning", "\"%1$s\" foi migrado para %4$s. O backup do armazenamento de chaves %2$s \u00E9 feito como \"%3$s\"."},
         {"backup.keystore.warning", "O backup do armazenamento de chaves original \"%1$s\" \u00E9 feito como \"%3$s\"..."},
--- a/src/share/classes/sun/security/tools/keytool/Resources_sv.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/security/tools/keytool/Resources_sv.java	Tue Jan 16 22:58:44 2018 -0800
@@ -435,19 +435,19 @@
         {"the.tsa.certificate", "TSA-certifikatet"},
         {"the.input", "Indata"},
         {"reply", "Svar"},
-        {"one.in.many", "%s %d av %d"},
+        {"one.in.many", "%1$s #%2$d av %3$d"},
         {"alias.in.cacerts", "Utf\u00E4rdaren <%s> i cacerts"},
         {"alias.in.keystore", "Utf\u00E4rdaren <%s>"},
         {"with.weak", "%s (svag)"},
-        {"key.bit", "%d-bitars %s-nyckel"},
-        {"key.bit.weak", "%d-bitars %s-nyckel (svag)"},
+        {"key.bit", "%1$d-bitars %2$s-nyckel"},
+        {"key.bit.weak", "%1$d-bitars %2$s-nyckel (svag)"},
         {".PATTERN.printX509Cert.with.weak",
                 "\u00C4gare: {0}\nUtf\u00E4rdare: {1}\nSerienummer: {2}\nGiltigt fr\u00E5n: {3}, till: {4}\nCertifikatfingeravtryck:\n\t MD5:  {5}\n\t SHA1: {6}\n\t SHA256: {7}\nSignaturalgoritmnamn: {8}\nAlgoritm f\u00F6r \u00E4mne f\u00F6r \u00F6ppen nyckel: {9}\nVersion: {10}"},
         {"PKCS.10.with.weak",
-                "PKCS #10-certifikatbeg\u00E4ran (version 1.0)\n\u00C4mne: %s\nFormat: %s\n\u00D6ppen nyckel: %s\nSignaturalgoritm: %s\n"},
-        {"verified.by.s.in.s.weak", "Verifierades av %s i %s med en %s"},
-        {"whose.sigalg.risk", "%s anv\u00E4nder signaturalgoritmen %s, vilket anses utg\u00F6ra en s\u00E4kerhetsrisk."},
-        {"whose.key.risk", "%s anv\u00E4nder en %s, vilket anses utg\u00F6ra en s\u00E4kerhetsrisk."},
+                "PKCS #10-certifikatbeg\u00E4ran (version 1.0)\n\u00C4mne: %1$s\nFormat: %2$s\n\u00D6ppen nyckel: %3$s\nSignaturalgoritm: %4$s\n"},
+        {"verified.by.s.in.s.weak", "Verifierades av %1$s i %2$s med en %3$s"},
+        {"whose.sigalg.risk", "%1$s anv\u00E4nder signaturalgoritmen %2$s, vilket anses utg\u00F6ra en s\u00E4kerhetsrisk."},
+        {"whose.key.risk", "%1$s anv\u00E4nder en %2$s, vilket anses utg\u00F6ra en s\u00E4kerhetsrisk."},
         {"jks.storetype.warning", "Nyckellagret %1$s anv\u00E4nder ett propriet\u00E4rt format. Du b\u00F6r migrera till PKCS12, som \u00E4r ett branschstandardformat, med \"keytool -importkeystore -srckeystore %2$s -destkeystore %2$s -deststoretype pkcs12\"."},
         {"migrate.keystore.warning", "Migrerade \"%1$s\" till %4$s. Nyckellagret %2$s s\u00E4kerhetskopierades som \"%3$s\"."},
         {"backup.keystore.warning", "Det ursprungliga nyckellagret, \"%1$s\", s\u00E4kerhetskopieras som \"%3$s\"..."},
--- a/src/share/classes/sun/security/tools/keytool/Resources_zh_CN.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/security/tools/keytool/Resources_zh_CN.java	Tue Jan 16 22:58:44 2018 -0800
@@ -435,19 +435,19 @@
         {"the.tsa.certificate", "TSA \u8BC1\u4E66"},
         {"the.input", "\u8F93\u5165"},
         {"reply", "\u56DE\u590D"},
-        {"one.in.many", "%s #%d/%d"},
+        {"one.in.many", "%1$s #%2$d/%3$d"},
         {"alias.in.cacerts", "cacerts \u4E2D\u7684\u53D1\u5E03\u8005 <%s>"},
         {"alias.in.keystore", "\u53D1\u5E03\u8005 <%s>"},
         {"with.weak", "%s (\u5F31)"},
-        {"key.bit", "%d \u4F4D %s \u5BC6\u94A5"},
-        {"key.bit.weak", "%d \u4F4D %s \u5BC6\u94A5 (\u5F31)"},
+        {"key.bit", "%1$d \u4F4D %2$s \u5BC6\u94A5"},
+        {"key.bit.weak", "%1$d \u4F4D %2$s \u5BC6\u94A5 (\u5F31)"},
         {".PATTERN.printX509Cert.with.weak",
                 "\u6240\u6709\u8005: {0}\n\u53D1\u5E03\u8005: {1}\n\u5E8F\u5217\u53F7: {2}\n\u6709\u6548\u671F\u4E3A {3} \u81F3 {4}\n\u8BC1\u4E66\u6307\u7EB9:\n\t MD5:  {5}\n\t SHA1: {6}\n\t SHA256: {7}\n\u7B7E\u540D\u7B97\u6CD5\u540D\u79F0: {8}\n\u4E3B\u4F53\u516C\u5171\u5BC6\u94A5\u7B97\u6CD5: {9}\n\u7248\u672C: {10}"},
         {"PKCS.10.with.weak",
-                "PKCS #10 \u8BC1\u4E66\u8BF7\u6C42 (\u7248\u672C 1.0)\n\u4E3B\u4F53: %s\n\u683C\u5F0F: %s\n\u516C\u5171\u5BC6\u94A5: %s\n\u7B7E\u540D\u7B97\u6CD5: %s\n"},
+                "PKCS #10 \u8BC1\u4E66\u8BF7\u6C42 (\u7248\u672C 1.0)\n\u4E3B\u4F53: %1$s\n\u683C\u5F0F: %2$s\n\u516C\u5171\u5BC6\u94A5: %3$s\n\u7B7E\u540D\u7B97\u6CD5: %4$s\n"},
         {"verified.by.s.in.s.weak", "\u7531 %2$s \u4E2D\u7684 %1$s \u4EE5 %3$s \u9A8C\u8BC1"},
-        {"whose.sigalg.risk", "%s \u4F7F\u7528\u7684 %s \u7B7E\u540D\u7B97\u6CD5\u5B58\u5728\u5B89\u5168\u98CE\u9669\u3002"},
-        {"whose.key.risk", "%s \u4F7F\u7528\u7684 %s \u5B58\u5728\u5B89\u5168\u98CE\u9669\u3002"},
+        {"whose.sigalg.risk", "%1$s \u4F7F\u7528\u7684 %2$s \u7B7E\u540D\u7B97\u6CD5\u5B58\u5728\u5B89\u5168\u98CE\u9669\u3002"},
+        {"whose.key.risk", "%1$s \u4F7F\u7528\u7684 %2$s \u5B58\u5728\u5B89\u5168\u98CE\u9669\u3002"},
         {"jks.storetype.warning", "%1$s \u5BC6\u94A5\u5E93\u4F7F\u7528\u4E13\u7528\u683C\u5F0F\u3002\u5EFA\u8BAE\u4F7F\u7528 \"keytool -importkeystore -srckeystore %2$s -destkeystore %2$s -deststoretype pkcs12\" \u8FC1\u79FB\u5230\u884C\u4E1A\u6807\u51C6\u683C\u5F0F PKCS12\u3002"},
         {"migrate.keystore.warning", "\u5DF2\u5C06 \"%1$s\" \u8FC1\u79FB\u5230 %4$s\u3002\u5C06 %2$s \u5BC6\u94A5\u5E93\u4F5C\u4E3A \"%3$s\" \u8FDB\u884C\u4E86\u5907\u4EFD\u3002"},
         {"backup.keystore.warning", "\u5DF2\u5C06\u539F\u59CB\u5BC6\u94A5\u5E93 \"%1$s\" \u5907\u4EFD\u4E3A \"%3$s\"..."},
--- a/src/share/classes/sun/security/tools/keytool/Resources_zh_TW.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/security/tools/keytool/Resources_zh_TW.java	Tue Jan 16 22:58:44 2018 -0800
@@ -435,19 +435,19 @@
         {"the.tsa.certificate", "TSA \u6191\u8B49"},
         {"the.input", "\u8F38\u5165"},
         {"reply", "\u56DE\u8986"},
-        {"one.in.many", "%s #%d / %d"},
+        {"one.in.many", "%1$s #%2$d / %3$d"},
         {"alias.in.cacerts", "cacerts \u4E2D\u7684\u767C\u884C\u4EBA <%s>"},
         {"alias.in.keystore", "\u767C\u884C\u4EBA <%s>"},
         {"with.weak", "%s (\u4F4E\u5F37\u5EA6)"},
-        {"key.bit", "%d \u4F4D\u5143\u7684 %s \u91D1\u9470"},
-        {"key.bit.weak", "%d \u4F4D\u5143\u7684 %s \u91D1\u9470 (\u4F4E\u5F37\u5EA6)"},
+        {"key.bit", "%1$d \u4F4D\u5143\u7684 %2$s \u91D1\u9470"},
+        {"key.bit.weak", "%1$d \u4F4D\u5143\u7684 %2$s \u91D1\u9470 (\u4F4E\u5F37\u5EA6)"},
         {".PATTERN.printX509Cert.with.weak",
                 "\u64C1\u6709\u8005: {0}\n\u767C\u884C\u4EBA: {1}\n\u5E8F\u865F: {2}\n\u6709\u6548\u671F\u81EA: {3} \u5230: {4}\n\u6191\u8B49\u6307\u7D0B:\n\t MD5:  {5}\n\t SHA1: {6}\n\t SHA256: {7}\n\u7C3D\u7AE0\u6F14\u7B97\u6CD5\u540D\u7A31: {8}\n\u4E3B\u9AD4\u516C\u958B\u91D1\u9470\u6F14\u7B97\u6CD5: {9}\n\u7248\u672C: {10}"},
         {"PKCS.10.with.weak",
-                "PKCS #10 \u6191\u8B49\u8981\u6C42 (\u7248\u672C 1.0)\n\u4E3B\u9AD4: %s\n\u683C\u5F0F: %s\n\u516C\u7528\u91D1\u9470: %s\n\u7C3D\u7AE0\u6F14\u7B97\u6CD5: %s\n"},
+                "PKCS #10 \u6191\u8B49\u8981\u6C42 (\u7248\u672C 1.0)\n\u4E3B\u9AD4: %1$s\n\u683C\u5F0F: %2$s\n\u516C\u7528\u91D1\u9470: %3$s\n\u7C3D\u7AE0\u6F14\u7B97\u6CD5: %4$s\n"},
         {"verified.by.s.in.s.weak", "\u7531 %2$s \u4E2D\u7684 %1$s \u4EE5 %3$s \u9A57\u8B49"},
-        {"whose.sigalg.risk", "%s \u4F7F\u7528\u7684 %s \u7C3D\u7AE0\u6F14\u7B97\u6CD5\u5B58\u5728\u5B89\u5168\u98A8\u96AA\u3002"},
-        {"whose.key.risk", "%s \u4F7F\u7528\u7684 %s \u5B58\u5728\u5B89\u5168\u98A8\u96AA\u3002"},
+        {"whose.sigalg.risk", "%1$s \u4F7F\u7528\u7684 %2$s \u7C3D\u7AE0\u6F14\u7B97\u6CD5\u5B58\u5728\u5B89\u5168\u98A8\u96AA\u3002"},
+        {"whose.key.risk", "%1$s \u4F7F\u7528\u7684 %2$s \u5B58\u5728\u5B89\u5168\u98A8\u96AA\u3002"},
         {"jks.storetype.warning", "%1$s \u91D1\u9470\u5132\u5B58\u5EAB\u4F7F\u7528\u5C08\u6709\u683C\u5F0F\u3002\u5EFA\u8B70\u60A8\u4F7F\u7528 \"keytool -importkeystore -srckeystore %2$s -destkeystore %2$s -deststoretype pkcs12\" \u79FB\u8F49\u6210\u70BA\u4F7F\u7528 PKCS12 (\u696D\u754C\u6A19\u6E96\u683C\u5F0F)\u3002"},
         {"migrate.keystore.warning", "\u5DF2\u5C07 \"%1$s\" \u79FB\u8F49\u6210\u70BA %4$s\u3002%2$s \u91D1\u9470\u5132\u5B58\u5EAB\u5DF2\u5099\u4EFD\u70BA \"%3$s\"\u3002"},
         {"backup.keystore.warning", "\u539F\u59CB\u7684\u91D1\u9470\u5132\u5B58\u5EAB \"%1$s\" \u5DF2\u5099\u4EFD\u70BA \"%3$s\"..."},
--- a/src/share/classes/sun/security/util/AlgorithmDecomposer.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/security/util/AlgorithmDecomposer.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2017, 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
@@ -27,6 +27,8 @@
 
 import java.util.HashSet;
 import java.util.Set;
+import java.util.Arrays;
+import java.util.Collection;
 import java.util.regex.Pattern;
 
 /**
@@ -133,6 +135,23 @@
         return elements;
     }
 
+    /**
+     * Get aliases of the specified algorithm.
+     *
+     * May support more algorithms in the future.
+     */
+    public static Collection<String> getAliases(String algorithm) {
+        String[] aliases;
+        if (algorithm.equalsIgnoreCase("DH") ||
+                algorithm.equalsIgnoreCase("DiffieHellman")) {
+            aliases = new String[] {"DH", "DiffieHellman"};
+        } else {
+            aliases = new String[] {algorithm};
+        }
+
+        return Arrays.asList(aliases);
+    }
+
     private static void hasLoop(Set<String> elements, String find, String replace) {
         if (elements.contains(find)) {
             if (!elements.contains(replace)) {
--- a/src/share/classes/sun/security/util/DerValue.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/security/util/DerValue.java	Tue Jan 16 22:58:44 2018 -0800
@@ -491,20 +491,27 @@
      * @return the octet string held in this DER value
      */
     public byte[] getOctetString() throws IOException {
-        byte[] bytes;
 
         if (tag != tag_OctetString && !isConstructed(tag_OctetString)) {
             throw new IOException(
                 "DerValue.getOctetString, not an Octet String: " + tag);
         }
-        bytes = new byte[length];
-        // Note: do not tempt to call buffer.read(bytes) at all. There's a
+        // Note: do not attempt to call buffer.read(bytes) at all. There's a
         // known bug that it returns -1 instead of 0.
         if (length == 0) {
-            return bytes;
+            return new byte[0];
         }
-        if (buffer.read(bytes) != length)
+
+        // Only allocate the array if there are enough bytes available.
+        // This only works for ByteArrayInputStream.
+        // The assignment below ensures that buffer has the required type.
+        ByteArrayInputStream arrayInput = buffer;
+        if (arrayInput.available() < length) {
             throw new IOException("short read on DerValue buffer");
+        }
+        byte[] bytes = new byte[length];
+        arrayInput.read(bytes);
+
         if (isConstructed()) {
             DerInputStream in = new DerInputStream(bytes, 0, bytes.length,
                 buffer.allowBER);
--- a/src/share/classes/sun/security/util/DisabledAlgorithmConstraints.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/security/util/DisabledAlgorithmConstraints.java	Tue Jan 16 22:58:44 2018 -0800
@@ -45,6 +45,7 @@
 import java.util.Locale;
 import java.util.Map;
 import java.util.Set;
+import java.util.Collection;
 import java.util.StringTokenizer;
 import java.util.TimeZone;
 import java.util.regex.Pattern;
@@ -106,7 +107,15 @@
     @Override
     public final boolean permits(Set<CryptoPrimitive> primitives,
             String algorithm, AlgorithmParameters parameters) {
-        return checkAlgorithm(disabledAlgorithms, algorithm, decomposer);
+        if (!checkAlgorithm(disabledAlgorithms, algorithm, decomposer)) {
+            return false;
+        }
+
+        if (parameters != null) {
+            return algorithmConstraints.permits(algorithm, parameters);
+        }
+
+        return true;
     }
 
     /*
@@ -242,7 +251,12 @@
                 List<Constraint> constraintList =
                         constraintsMap.getOrDefault(algorithm,
                                 new ArrayList<>(1));
-                constraintsMap.putIfAbsent(algorithm, constraintList);
+
+                // Consider the impact of algorithm aliases.
+                for (String alias : AlgorithmDecomposer.getAliases(algorithm)) {
+                    constraintsMap.putIfAbsent(alias, constraintList);
+                }
+
                 if (space <= 0) {
                     constraintList.add(new DisabledConstraint(algorithm));
                     continue;
@@ -351,6 +365,27 @@
             return true;
         }
 
+        // Check if constraints permit this AlgorithmParameters.
+        public boolean permits(String algorithm, AlgorithmParameters aps) {
+            List<Constraint> list = getConstraints(algorithm);
+            if (list == null) {
+                return true;
+            }
+
+            for (Constraint constraint : list) {
+                if (!constraint.permits(aps)) {
+                    if (debug != null) {
+                        debug.println("keySizeConstraint: failed algorithm " +
+                                "parameters constraint check " + aps);
+                    }
+
+                    return false;
+                }
+            }
+
+            return true;
+        }
+
         // Check if constraints permit this cert.
         public void permits(String algorithm, ConstraintsParameters cp)
                 throws CertPathValidatorException {
@@ -445,6 +480,18 @@
         }
 
         /**
+         * Check if the algorithm constraint permits a given cryptographic
+         * parameters.
+         *
+         * @param parameters the cryptographic parameters
+         * @return 'true' if the cryptographic parameters is allowed,
+         *         'false' ortherwise.
+         */
+        public boolean permits(AlgorithmParameters parameters) {
+            return true;
+        }
+
+        /**
          * Check if an algorithm constraint is permitted with a given
          * ConstraintsParameters.
          *
@@ -528,6 +575,7 @@
          * call next() for any following constraints. If it does not, exit
          * as this constraint(s) does not restrict the operation.
          */
+        @Override
         public void permits(ConstraintsParameters cp)
                 throws CertPathValidatorException {
             if (debug != null) {
@@ -551,100 +599,101 @@
      * This class handles the denyAfter constraint.  The date is in the UTC/GMT
      * timezone.
      */
-     private static class DenyAfterConstraint extends Constraint {
-         private Date denyAfterDate;
-         private static final SimpleDateFormat dateFormat =
-                 new SimpleDateFormat("EEE, MMM d HH:mm:ss z yyyy");
+    private static class DenyAfterConstraint extends Constraint {
+        private Date denyAfterDate;
+        private static final SimpleDateFormat dateFormat =
+                new SimpleDateFormat("EEE, MMM d HH:mm:ss z yyyy");
 
-         DenyAfterConstraint(String algo, int year, int month, int day) {
-             Calendar c;
+        DenyAfterConstraint(String algo, int year, int month, int day) {
+            Calendar c;
 
-             algorithm = algo;
+            algorithm = algo;
 
-             if (debug != null) {
-                 debug.println("DenyAfterConstraint read in as:  year " +
-                         year + ", month = " + month + ", day = " + day);
-             }
+            if (debug != null) {
+                debug.println("DenyAfterConstraint read in as:  year " +
+                        year + ", month = " + month + ", day = " + day);
+            }
 
-             c = new Calendar.Builder().setTimeZone(TimeZone.getTimeZone("GMT"))
-                     .setDate(year, month - 1, day).build();
+            c = new Calendar.Builder().setTimeZone(TimeZone.getTimeZone("GMT"))
+                    .setDate(year, month - 1, day).build();
 
-             if (year > c.getActualMaximum(Calendar.YEAR) ||
-                     year < c.getActualMinimum(Calendar.YEAR)) {
-                 throw new IllegalArgumentException(
-                         "Invalid year given in constraint: " + year);
-             }
-             if ((month - 1) > c.getActualMaximum(Calendar.MONTH) ||
-                     (month - 1) < c.getActualMinimum(Calendar.MONTH)) {
-                 throw new IllegalArgumentException(
-                         "Invalid month given in constraint: " + month);
-             }
-             if (day > c.getActualMaximum(Calendar.DAY_OF_MONTH) ||
-                     day < c.getActualMinimum(Calendar.DAY_OF_MONTH)) {
-                 throw new IllegalArgumentException(
-                         "Invalid Day of Month given in constraint: " + day);
-             }
+            if (year > c.getActualMaximum(Calendar.YEAR) ||
+                    year < c.getActualMinimum(Calendar.YEAR)) {
+                throw new IllegalArgumentException(
+                        "Invalid year given in constraint: " + year);
+            }
+            if ((month - 1) > c.getActualMaximum(Calendar.MONTH) ||
+                    (month - 1) < c.getActualMinimum(Calendar.MONTH)) {
+                throw new IllegalArgumentException(
+                        "Invalid month given in constraint: " + month);
+            }
+            if (day > c.getActualMaximum(Calendar.DAY_OF_MONTH) ||
+                    day < c.getActualMinimum(Calendar.DAY_OF_MONTH)) {
+                throw new IllegalArgumentException(
+                        "Invalid Day of Month given in constraint: " + day);
+            }
 
-             denyAfterDate = c.getTime();
-             if (debug != null) {
-                 debug.println("DenyAfterConstraint date set to: " +
-                         dateFormat.format(denyAfterDate));
-             }
-         }
+            denyAfterDate = c.getTime();
+            if (debug != null) {
+                debug.println("DenyAfterConstraint date set to: " +
+                        dateFormat.format(denyAfterDate));
+            }
+        }
 
-         /*
-          * Checking that the provided date is not beyond the constraint date.
-          * The provided date can be the PKIXParameter date if given,
-          * otherwise it is the current date.
-          *
-          * If the constraint disallows, call next() for any following
-          * constraints. Throw an exception if this is the last constraint.
-          */
-         @Override
-         public void permits(ConstraintsParameters cp)
-                 throws CertPathValidatorException {
-             Date currentDate;
-             String errmsg;
+        /*
+         * Checking that the provided date is not beyond the constraint date.
+         * The provided date can be the PKIXParameter date if given,
+         * otherwise it is the current date.
+         *
+         * If the constraint disallows, call next() for any following
+         * constraints. Throw an exception if this is the last constraint.
+         */
+        @Override
+        public void permits(ConstraintsParameters cp)
+                throws CertPathValidatorException {
+            Date currentDate;
+            String errmsg;
 
-             if (cp.getJARTimestamp() != null) {
-                 currentDate = cp.getJARTimestamp().getTimestamp();
-                 errmsg = "JAR Timestamp date: ";
-             } else if (cp.getPKIXParamDate() != null) {
-                 currentDate = cp.getPKIXParamDate();
-                 errmsg = "PKIXParameter date: ";
-             } else {
-                 currentDate = new Date();
-                 errmsg = "Current date: ";
-             }
+            if (cp.getJARTimestamp() != null) {
+                currentDate = cp.getJARTimestamp().getTimestamp();
+                errmsg = "JAR Timestamp date: ";
+            } else if (cp.getPKIXParamDate() != null) {
+                currentDate = cp.getPKIXParamDate();
+                errmsg = "PKIXParameter date: ";
+            } else {
+                currentDate = new Date();
+                errmsg = "Current date: ";
+            }
 
-             if (!denyAfterDate.after(currentDate)) {
-                 if (next(cp)) {
-                     return;
-                 }
-                 throw new CertPathValidatorException(
-                         "denyAfter constraint check failed: " + algorithm +
-                         " used with Constraint date: " +
-                         dateFormat.format(denyAfterDate) + "; " + errmsg +
-                         dateFormat.format(currentDate) + extendedMsg(cp),
-                         null, null, -1, BasicReason.ALGORITHM_CONSTRAINED);
-             }
-         }
+            if (!denyAfterDate.after(currentDate)) {
+                if (next(cp)) {
+                    return;
+                }
+                throw new CertPathValidatorException(
+                        "denyAfter constraint check failed: " + algorithm +
+                        " used with Constraint date: " +
+                        dateFormat.format(denyAfterDate) + "; " + errmsg +
+                        dateFormat.format(currentDate) + extendedMsg(cp),
+                        null, null, -1, BasicReason.ALGORITHM_CONSTRAINED);
+            }
+        }
 
-         /*
-          * Return result if the constraint's date is beyond the current date
-          * in UTC timezone.
-          */
-         public boolean permits(Key key) {
-             if (next(key)) {
-                 return true;
-             }
-             if (debug != null) {
-                 debug.println("DenyAfterConstraints.permits(): " + algorithm);
-             }
+        /*
+         * Return result if the constraint's date is beyond the current date
+         * in UTC timezone.
+         */
+        @Override
+        public boolean permits(Key key) {
+            if (next(key)) {
+                return true;
+            }
+            if (debug != null) {
+                debug.println("DenyAfterConstraints.permits(): " + algorithm);
+            }
 
-             return denyAfterDate.after(new Date());
-         }
-     }
+            return denyAfterDate.after(new Date());
+        }
+    }
 
     /*
      * The usage constraint is for the "usage" keyword.  It checks against the
@@ -658,6 +707,7 @@
             this.usages = usages;
         }
 
+        @Override
         public void permits(ConstraintsParameters cp)
                 throws CertPathValidatorException {
             for (String usage : usages) {
@@ -747,6 +797,7 @@
          * constraint  Any permitted constraint will exit the linked list
          * to allow the operation.
          */
+        @Override
         public void permits(ConstraintsParameters cp)
                 throws CertPathValidatorException {
             Key key = null;
@@ -771,6 +822,7 @@
 
         // Check if key constraint disable the specified key
         // Uses old style permit()
+        @Override
         public boolean permits(Key key) {
             // If we recursively find a constraint that permits us to use
             // this key, return true and skip any other constraint checks.
@@ -784,6 +836,30 @@
             return permitsImpl(key);
         }
 
+        @Override
+        public boolean permits(AlgorithmParameters parameters) {
+            String paramAlg = parameters.getAlgorithm();
+            if (!algorithm.equalsIgnoreCase(parameters.getAlgorithm())) {
+                // Consider the impact of the algorithm aliases.
+                Collection<String> aliases =
+                        AlgorithmDecomposer.getAliases(algorithm);
+                if (!aliases.contains(paramAlg)) {
+                    return true;
+                }
+            }
+
+            int keySize = KeyUtil.getKeySize(parameters);
+            if (keySize == 0) {
+                return false;
+            } else if (keySize > 0) {
+                return !((keySize < minSize) || (keySize > maxSize) ||
+                    (prohibitedSize == keySize));
+            }   // Otherwise, the key size is not accessible or determined.
+                // Conservatively, please don't disable such keys.
+
+            return true;
+        }
+
         private boolean permitsImpl(Key key) {
             // Verify this constraint is for this public key algorithm
             if (algorithm.compareToIgnoreCase(key.getAlgorithm()) != 0) {
@@ -811,6 +887,7 @@
             algorithm = algo;
         }
 
+        @Override
         public void permits(ConstraintsParameters cp)
                 throws CertPathValidatorException {
             throw new CertPathValidatorException(
@@ -819,6 +896,7 @@
                     null, null, -1, BasicReason.ALGORITHM_CONSTRAINED);
         }
 
+        @Override
         public boolean permits(Key key) {
             return false;
         }
--- a/src/share/classes/sun/security/util/KeyUtil.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/security/util/KeyUtil.java	Tue Jan 16 22:58:44 2018 -0800
@@ -25,6 +25,7 @@
 
 package sun.security.util;
 
+import java.security.AlgorithmParameters;
 import java.security.Key;
 import java.security.PrivilegedAction;
 import java.security.AccessController;
@@ -35,6 +36,8 @@
 import java.security.interfaces.DSAParams;
 import java.security.SecureRandom;
 import java.security.spec.KeySpec;
+import java.security.spec.ECParameterSpec;
+import java.security.spec.InvalidParameterSpecException;
 import javax.crypto.SecretKey;
 import javax.crypto.interfaces.DHKey;
 import javax.crypto.interfaces.DHPublicKey;
@@ -100,6 +103,61 @@
     }
 
     /**
+     * Returns the key size of the given cryptographic parameters in bits.
+     *
+     * @param parameters the cryptographic parameters, cannot be null
+     * @return the key size of the given cryptographic parameters in bits,
+     *       or -1 if the key size is not accessible
+     */
+    public static final int getKeySize(AlgorithmParameters parameters) {
+
+        String algorithm = parameters.getAlgorithm();
+        switch (algorithm) {
+            case "EC":
+                try {
+                    ECKeySizeParameterSpec ps = parameters.getParameterSpec(
+                            ECKeySizeParameterSpec.class);
+                    if (ps != null) {
+                        return ps.getKeySize();
+                    }
+                } catch (InvalidParameterSpecException ipse) {
+                    // ignore
+                }
+
+                try {
+                    ECParameterSpec ps = parameters.getParameterSpec(
+                            ECParameterSpec.class);
+                    if (ps != null) {
+                        return ps.getOrder().bitLength();
+                    }
+                } catch (InvalidParameterSpecException ipse) {
+                    // ignore
+                }
+
+                // Note: the ECGenParameterSpec case should be covered by the
+                // ECParameterSpec case above.
+                // See ECUtil.getECParameterSpec(Provider, String).
+
+                break;
+            case "DiffieHellman":
+                try {
+                    DHParameterSpec ps = parameters.getParameterSpec(
+                            DHParameterSpec.class);
+                    if (ps != null) {
+                        return ps.getP().bitLength();
+                    }
+                } catch (InvalidParameterSpecException ipse) {
+                    // ignore
+                }
+                break;
+
+            // May support more AlgorithmParameters algorithms in the future.
+        }
+
+        return -1;
+    }
+
+    /**
      * Returns whether the key is valid or not.
      * <P>
      * Note that this method is only apply to DHPublicKey at present.
--- a/src/share/classes/sun/security/util/SecurityProviderConstants.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/security/util/SecurityProviderConstants.java	Tue Jan 16 22:58:44 2018 -0800
@@ -64,9 +64,9 @@
     static {
         String keyLengthStr = GetPropertyAction.privilegedGetProperty
             (KEY_LENGTH_PROP);
-        int dsaKeySize = 1024;
-        int rsaKeySize = 1024;
-        int dhKeySize = 1024;
+        int dsaKeySize = 2048;
+        int rsaKeySize = 2048;
+        int dhKeySize = 2048;
         int ecKeySize = 256;
 
         if (keyLengthStr != null) {
--- a/src/share/classes/sun/tools/jar/resources/jar_ko.properties	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/classes/sun/tools/jar/resources/jar_ko.properties	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 1999, 2016, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 1999, 2017, 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
@@ -45,4 +45,4 @@
 out.inflated=\ \uC99D\uAC00\uB428: {0}
 out.size=(\uC785\uB825 = {0}) (\uCD9C\uB825 = {1})
 
-usage=\uC0AC\uC6A9\uBC95: jar {ctxui}[vfmn0PMe] [jar-file] [manifest-file] [entry-point] [-C dir] files ...\n\uC635\uC158:\n    -c  \uC0C8 \uC544\uCE74\uC774\uBE0C\uB97C \uC0DD\uC131\uD569\uB2C8\uB2E4.\n    -t  \uC544\uCE74\uC774\uBE0C\uC5D0 \uB300\uD55C \uBAA9\uCC28\uB97C \uB098\uC5F4\uD569\uB2C8\uB2E4.\n    -x  \uBA85\uBA85\uB41C(\uB610\uB294 \uBAA8\uB4E0) \uD30C\uC77C\uC744 \uC544\uCE74\uC774\uBE0C\uC5D0\uC11C \uCD94\uCD9C\uD569\uB2C8\uB2E4.\n    -u  \uAE30\uC874 \uC544\uCE74\uC774\uBE0C\uB97C \uC5C5\uB370\uC774\uD2B8\uD569\uB2C8\uB2E4.\n    -v  \uD45C\uC900 \uCD9C\uB825\uC5D0 \uC0C1\uC138 \uC815\uBCF4 \uCD9C\uB825\uC744 \uC0DD\uC131\uD569\uB2C8\uB2E4.\n    -f  \uC544\uCE74\uC774\uBE0C \uD30C\uC77C \uC774\uB984\uC744 \uC9C0\uC815\uD569\uB2C8\uB2E4.\n    -m  \uC9C0\uC815\uB41C Manifest \uD30C\uC77C\uC758 Manifest \uC815\uBCF4\uB97C \uD3EC\uD568\uD569\uB2C8\uB2E4.\n    -n  \uC0C8 \uC544\uCE74\uC774\uBE0C\uB97C \uC0DD\uC131\uD55C \uD6C4 Pack200 \uC815\uADDC\uD654\uB97C \uC218\uD589\uD569\uB2C8\uB2E4.\n    -e  jar \uC2E4\uD589 \uD30C\uC77C\uC5D0 \uBC88\uB4E4\uB85C \uC81C\uACF5\uB41C \uB3C5\uB9BD\uD615 \uC560\uD50C\uB9AC\uCF00\uC774\uC158\uC758 \n        \uC560\uD50C\uB9AC\uCF00\uC774\uC158 \uC2DC\uC791 \uC9C0\uC810\uC744 \uC9C0\uC815\uD569\uB2C8\uB2E4.\n    -0  \uC800\uC7A5 \uC804\uC6A9: ZIP \uC555\uCD95\uC744 \uC0AC\uC6A9\uD558\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.\n    -P  \uD30C\uC77C \uC774\uB984\uC5D0\uC11C \uC120\uD589 '/'(\uC808\uB300 \uACBD\uB85C) \uBC0F ".."(\uC0C1\uC704 \uB514\uB809\uD1A0\uB9AC) \uAD6C\uC131 \uC694\uC18C\uB97C \uC720\uC9C0\uD569\uB2C8\uB2E4.\n    -M  \uD56D\uBAA9\uC5D0 \uB300\uD574 Manifest \uD30C\uC77C\uC744 \uC0DD\uC131\uD558\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.\n    -i  \uC9C0\uC815\uB41C jar \uD30C\uC77C\uC5D0 \uB300\uD55C \uC778\uB371\uC2A4 \uC815\uBCF4\uB97C \uC0DD\uC131\uD569\uB2C8\uB2E4.\n    -C  \uC9C0\uC815\uB41C \uB514\uB809\uD1A0\uB9AC\uB85C \uBCC0\uACBD\uD558\uACE0 \uB2E4\uC74C \uD30C\uC77C\uC744 \uD3EC\uD568\uD569\uB2C8\uB2E4.\n\uD2B9\uC815 \uD30C\uC77C\uC774 \uB514\uB809\uD1A0\uB9AC\uC77C \uACBD\uC6B0 \uC21C\uD658\uC801\uC73C\uB85C \uCC98\uB9AC\uB429\uB2C8\uB2E4.\nManifest \uD30C\uC77C \uC774\uB984, \uC544\uCE74\uC774\uBE0C \uD30C\uC77C \uC774\uB984 \uBC0F \uC2DC\uC791 \uC9C0\uC810 \uC774\uB984\uC740\n'm', 'f' \uBC0F 'e' \uD50C\uB798\uADF8\uC640 \uB3D9\uC77C\uD55C \uC21C\uC11C\uB85C \uC9C0\uC815\uB429\uB2C8\uB2E4.\n\n\uC608 1: classes.jar\uB77C\uB294 \uC544\uCE74\uC774\uBE0C\uC5D0 \uB450 \uD074\uB798\uC2A4 \uD30C\uC77C\uC744 \uC544\uCE74\uC774\uBE0C\uD558\uB294 \uBC29\uBC95: \n       jar cvf classes.jar Foo.class Bar.class \n\uC608 2: \uAE30\uC874 Manifest \uD30C\uC77C 'mymanifest'\uB97C \uC0AC\uC6A9\uD558\uC5EC\n           foo/ \uB514\uB809\uD1A0\uB9AC\uC758 \uBAA8\uB4E0 \uD30C\uC77C\uC744 'classes.jar'\uB85C \uC544\uCE74\uC774\uBE0C\uD558\uB294 \uBC29\uBC95: \n       jar cvfm classes.jar mymanifest -C foo/ .
+usage=\uC0AC\uC6A9\uBC95: jar {ctxui}[vfmn0PMe] [jar-file] [manifest-file] [entry-point] [-C dir] files ...\n\uC635\uC158:\n    -c  \uC0C8 \uC544\uCE74\uC774\uBE0C\uB97C \uC0DD\uC131\uD569\uB2C8\uB2E4.\n    -t  \uC544\uCE74\uC774\uBE0C\uC5D0 \uB300\uD55C \uBAA9\uCC28\uB97C \uB098\uC5F4\uD569\uB2C8\uB2E4.\n    -x  \uBA85\uBA85\uB41C(\uB610\uB294 \uBAA8\uB4E0) \uD30C\uC77C\uC744 \uC544\uCE74\uC774\uBE0C\uC5D0\uC11C \uCD94\uCD9C\uD569\uB2C8\uB2E4.\n    -u  \uAE30\uC874 \uC544\uCE74\uC774\uBE0C\uB97C \uC5C5\uB370\uC774\uD2B8\uD569\uB2C8\uB2E4.\n    -v  \uD45C\uC900 \uCD9C\uB825\uC5D0 \uC0C1\uC138 \uC815\uBCF4 \uCD9C\uB825\uC744 \uC0DD\uC131\uD569\uB2C8\uB2E4.\n    -f  \uC544\uCE74\uC774\uBE0C \uD30C\uC77C \uC774\uB984\uC744 \uC9C0\uC815\uD569\uB2C8\uB2E4.\n    -m  \uC9C0\uC815\uB41C Manifest \uD30C\uC77C\uC758 Manifest \uC815\uBCF4\uB97C \uD3EC\uD568\uD569\uB2C8\uB2E4.\n    -n  \uC0C8 \uC544\uCE74\uC774\uBE0C\uB97C \uC0DD\uC131\uD55C \uD6C4 Pack200 \uC815\uADDC\uD654\uB97C \uC218\uD589\uD569\uB2C8\uB2E4.\n    -e  jar \uC2E4\uD589 \uD30C\uC77C\uC5D0 \uBC88\uB4E4\uB85C \uC81C\uACF5\uB41C \uB3C5\uB9BD\uD615 \uC560\uD50C\uB9AC\uCF00\uC774\uC158\uC758 \n        \uC560\uD50C\uB9AC\uCF00\uC774\uC158 \uC2DC\uC791 \uC9C0\uC810\uC744 \uC9C0\uC815\uD569\uB2C8\uB2E4.\n    -0  \uC800\uC7A5 \uC804\uC6A9: ZIP \uC555\uCD95\uC744 \uC0AC\uC6A9\uD558\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.\n    -P  \uD30C\uC77C \uC774\uB984\uC5D0\uC11C \uC120\uD589 '/'(\uC808\uB300 \uACBD\uB85C) \uBC0F ".."(\uC0C1\uC704 \uB514\uB809\uD1A0\uB9AC) \uAD6C\uC131\uC694\uC18C\uB97C \uC720\uC9C0\uD569\uB2C8\uB2E4.\n    -M  \uD56D\uBAA9\uC5D0 \uB300\uD574 Manifest \uD30C\uC77C\uC744 \uC0DD\uC131\uD558\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.\n    -i  \uC9C0\uC815\uB41C jar \uD30C\uC77C\uC5D0 \uB300\uD55C \uC778\uB371\uC2A4 \uC815\uBCF4\uB97C \uC0DD\uC131\uD569\uB2C8\uB2E4.\n    -C  \uC9C0\uC815\uB41C \uB514\uB809\uD1A0\uB9AC\uB85C \uBCC0\uACBD\uD558\uACE0 \uB2E4\uC74C \uD30C\uC77C\uC744 \uD3EC\uD568\uD569\uB2C8\uB2E4.\n\uD2B9\uC815 \uD30C\uC77C\uC774 \uB514\uB809\uD1A0\uB9AC\uC77C \uACBD\uC6B0 \uC21C\uD658\uC801\uC73C\uB85C \uCC98\uB9AC\uB429\uB2C8\uB2E4.\nManifest \uD30C\uC77C \uC774\uB984, \uC544\uCE74\uC774\uBE0C \uD30C\uC77C \uC774\uB984 \uBC0F \uC2DC\uC791 \uC9C0\uC810 \uC774\uB984\uC740\n'm', 'f' \uBC0F 'e' \uD50C\uB798\uADF8\uC640 \uB3D9\uC77C\uD55C \uC21C\uC11C\uB85C \uC9C0\uC815\uB429\uB2C8\uB2E4.\n\n\uC608 1: classes.jar\uB77C\uB294 \uC544\uCE74\uC774\uBE0C\uC5D0 \uB450 \uD074\uB798\uC2A4 \uD30C\uC77C\uC744 \uC544\uCE74\uC774\uBE0C\uD558\uB294 \uBC29\uBC95: \n       jar cvf classes.jar Foo.class Bar.class \n\uC608 2: \uAE30\uC874 Manifest \uD30C\uC77C 'mymanifest'\uB97C \uC0AC\uC6A9\uD558\uC5EC\n           foo/ \uB514\uB809\uD1A0\uB9AC\uC758 \uBAA8\uB4E0 \uD30C\uC77C\uC744 'classes.jar'\uB85C \uC544\uCE74\uC774\uBE0C\uD558\uB294 \uBC29\uBC95: \n       jar cvfm classes.jar mymanifest -C foo/ .
--- a/src/share/lib/management/management.properties	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/lib/management/management.properties	Tue Jan 16 22:58:44 2018 -0800
@@ -329,3 +329,38 @@
 #      The format of the value for that property is any string accepted
 #      by java.net.InetAddress.getByName(String).
 #
+
+# ################ Filter for ObjectInputStream #############################
+# com.sun.management.jmxremote.serial.filter.pattern=<filter-string>
+#   A filter, if configured, is used by java.io.ObjectInputStream during
+#   deserialization of parameters sent to the JMX default agent to validate the 
+#   contents of the stream.
+#   A filter is configured as a sequence of patterns, each pattern is either
+#   matched against the name of a class in the stream or defines a limit.
+#   Patterns are separated by ";" (semicolon).
+#   Whitespace is significant and is considered part of the pattern.
+#
+#   If a pattern includes a "=", it sets a limit.
+#   If a limit appears more than once the last value is used.
+#   Limits are checked before classes regardless of the order in the sequence of patterns.
+#   If any of the limits are exceeded, the filter status is REJECTED.
+#
+#       maxdepth=value - the maximum depth of a graph
+#       maxrefs=value  - the maximum number of internal references
+#       maxbytes=value - the maximum number of bytes in the input stream
+#       maxarray=value - the maximum array length allowed
+#
+#   Other patterns, from left to right, match the class or package name as
+#   returned from Class.getName.
+#   If the class is an array type, the class or package to be matched is the element type.
+#   Arrays of any number of dimensions are treated the same as the element type.
+#   For example, a pattern of "!example.Foo", rejects creation of any instance or
+#   array of example.Foo.
+#
+#   If the pattern starts with "!", the status is REJECTED if the remaining pattern
+#       is matched; otherwise the status is ALLOWED if the pattern matches.
+#   If the pattern ends with ".**" it matches any class in the package and all subpackages.
+#   If the pattern ends with ".*" it matches any class in the package.
+#   If the pattern ends with "*", it matches any class with the pattern as a prefix.
+#   If the pattern is equal to the class name, it matches.
+#   Otherwise, the status is UNDECIDED.
--- a/src/share/lib/security/java.security-aix	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/lib/security/java.security-aix	Tue Jan 16 22:58:44 2018 -0800
@@ -222,6 +222,7 @@
                jdk.internal.,\
                jdk.nashorn.internal.,\
                jdk.nashorn.tools.,\
+               jdk.xml.internal.,\
                com.sun.activation.registries.
 
 #
@@ -271,6 +272,7 @@
                    jdk.internal.,\
                    jdk.nashorn.internal.,\
                    jdk.nashorn.tools.,\
+                   jdk.xml.internal.,\
                    com.sun.activation.registries.
 
 #
@@ -585,7 +587,7 @@
 #
 # See "jdk.certpath.disabledAlgorithms" for syntax descriptions.
 #
-jdk.jar.disabledAlgorithms=MD2, MD5, RSA keySize < 1024
+jdk.jar.disabledAlgorithms=MD2, MD5, RSA keySize < 1024, DSA keySize < 1024
 
 #
 # Algorithm restrictions for Secure Socket Layer/Transport Layer Security
@@ -617,8 +619,8 @@
 #
 # Example:
 #   jdk.tls.disabledAlgorithms=MD5, SSLv3, DSA, RSA keySize < 2048
-jdk.tls.disabledAlgorithms=SSLv3, RC4, MD5withRSA, DH keySize < 768, \
-    EC keySize < 224
+jdk.tls.disabledAlgorithms=SSLv3, RC4, MD5withRSA, DH keySize < 1024, \
+    EC keySize < 224, DES40_CBC, RC4_40
 
 # Legacy algorithms for Secure Socket Layer/Transport Layer Security (SSL/TLS)
 # processing in JSSE implementation.
@@ -672,8 +674,6 @@
 #
 jdk.tls.legacyAlgorithms= \
         K_NULL, C_NULL, M_NULL, \
-        DHE_DSS_EXPORT, DHE_RSA_EXPORT, DH_anon_EXPORT, DH_DSS_EXPORT, \
-        DH_RSA_EXPORT, RSA_EXPORT, \
         DH_anon, ECDH_anon, \
         RC4_128, RC4_40, DES_CBC, DES40_CBC, \
         3DES_EDE_CBC
@@ -933,3 +933,24 @@
 #    java.rmi.dgc.VMID;\
 #    java.rmi.dgc.Lease;\
 #    maxdepth=5;maxarray=10000
+
+# CORBA ORBIorTypeCheckRegistryFilter
+# Type check enhancement for ORB::string_to_object processing
+#
+# An IOR type check filter, if configured, is used by an ORB during
+# an ORB::string_to_object invocation to check the veracity of the type encoded
+# in the ior string.
+#
+# The filter pattern consists of a semi-colon separated list of class names.
+# The configured list contains the binary class names of the IDL interface types
+# corresponding to the IDL stub class to be instantiated.
+# As such, a filter specifies a list of IDL stub classes that will be
+# allowed by an ORB when an ORB::string_to_object is invoked.
+# It is used to specify a white list configuration of acceptable
+# IDL stub types which may be contained in a stringified IOR
+# parameter passed as input to an ORB::string_to_object method.
+#
+# Note: This property is currently used by the JDK Reference implementation.
+# It is not guaranteed to be examined and used by other implementations.
+#
+#com.sun.CORBA.ORBIorTypeCheckRegistryFilter=binary_class_name;binary_class_name
--- a/src/share/lib/security/java.security-linux	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/lib/security/java.security-linux	Tue Jan 16 22:58:44 2018 -0800
@@ -222,6 +222,7 @@
                jdk.internal.,\
                jdk.nashorn.internal.,\
                jdk.nashorn.tools.,\
+               jdk.xml.internal.,\
                com.sun.activation.registries.
 
 #
@@ -271,6 +272,7 @@
                    jdk.internal.,\
                    jdk.nashorn.internal.,\
                    jdk.nashorn.tools.,\
+                   jdk.xml.internal.,\
                    com.sun.activation.registries.
 
 #
@@ -585,7 +587,7 @@
 #
 # See "jdk.certpath.disabledAlgorithms" for syntax descriptions.
 #
-jdk.jar.disabledAlgorithms=MD2, MD5, RSA keySize < 1024
+jdk.jar.disabledAlgorithms=MD2, MD5, RSA keySize < 1024, DSA keySize < 1024
 
 #
 # Algorithm restrictions for Secure Socket Layer/Transport Layer Security
@@ -617,8 +619,8 @@
 #
 # Example:
 #   jdk.tls.disabledAlgorithms=MD5, SSLv3, DSA, RSA keySize < 2048
-jdk.tls.disabledAlgorithms=SSLv3, RC4, MD5withRSA, DH keySize < 768, \
-    EC keySize < 224
+jdk.tls.disabledAlgorithms=SSLv3, RC4, MD5withRSA, DH keySize < 1024, \
+    EC keySize < 224, DES40_CBC, RC4_40
 
 # Legacy algorithms for Secure Socket Layer/Transport Layer Security (SSL/TLS)
 # processing in JSSE implementation.
@@ -672,8 +674,6 @@
 #
 jdk.tls.legacyAlgorithms= \
         K_NULL, C_NULL, M_NULL, \
-        DHE_DSS_EXPORT, DHE_RSA_EXPORT, DH_anon_EXPORT, DH_DSS_EXPORT, \
-        DH_RSA_EXPORT, RSA_EXPORT, \
         DH_anon, ECDH_anon, \
         RC4_128, RC4_40, DES_CBC, DES40_CBC, \
         3DES_EDE_CBC
@@ -885,6 +885,8 @@
 # If the pattern is equal to the class name, it matches.
 # Otherwise, the status is UNDECIDED.
 #
+# Primitive types are not configurable with this filter.
+#
 #jdk.serialFilter=pattern;pattern
 
 #
@@ -896,9 +898,12 @@
 # to increase limits.
 # If the limits (maxdepth, maxrefs, or maxbytes) are exceeded, the object is rejected.
 #
-# Each non-array type is allowed or rejected if it matches one of the patterns,
-# evaluated from left to right, and is otherwise allowed. Arrays of any
-# component type, including subarrays and arrays of primitives, are allowed.
+# The maxdepth of any array passed to the RMI Registry is set to
+# 10000.  The maximum depth of the graph is set to 20.
+# These limits can be reduced via the maxarray, maxdepth limits.
+#
+#sun.rmi.registry.registryFilter=pattern;pattern
+
 #
 # Array construction of any component type, including subarrays and arrays of
 # primitives, are allowed unless the length is greater than the maxarray limit.
@@ -935,3 +940,23 @@
 #    java.rmi.dgc.Lease;\
 #    maxdepth=5;maxarray=10000
 
+# CORBA ORBIorTypeCheckRegistryFilter
+# Type check enhancement for ORB::string_to_object processing
+#
+# An IOR type check filter, if configured, is used by an ORB during
+# an ORB::string_to_object invocation to check the veracity of the type encoded
+# in the ior string.
+#
+# The filter pattern consists of a semi-colon separated list of class names.
+# The configured list contains the binary class names of the IDL interface types
+# corresponding to the IDL stub class to be instantiated.
+# As such, a filter specifies a list of IDL stub classes that will be
+# allowed by an ORB when an ORB::string_to_object is invoked.
+# It is used to specify a white list configuration of acceptable
+# IDL stub types which may be contained in a stringified IOR
+# parameter passed as input to an ORB::string_to_object method.
+#
+# Note: This property is currently used by the JDK Reference implementation.
+# It is not guaranteed to be examined and used by other implementations.
+#
+#com.sun.CORBA.ORBIorTypeCheckRegistryFilter=binary_class_name;binary_class_name
--- a/src/share/lib/security/java.security-macosx	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/lib/security/java.security-macosx	Tue Jan 16 22:58:44 2018 -0800
@@ -223,6 +223,7 @@
                jdk.internal.,\
                jdk.nashorn.internal.,\
                jdk.nashorn.tools.,\
+               jdk.xml.internal.,\
                com.sun.activation.registries.,\
                apple.
 
@@ -273,6 +274,7 @@
                    jdk.internal.,\
                    jdk.nashorn.internal.,\
                    jdk.nashorn.tools.,\
+                   jdk.xml.internal.,\
                    com.sun.activation.registries.,\
                    apple.
 
@@ -588,7 +590,7 @@
 #
 # See "jdk.certpath.disabledAlgorithms" for syntax descriptions.
 #
-jdk.jar.disabledAlgorithms=MD2, MD5, RSA keySize < 1024
+jdk.jar.disabledAlgorithms=MD2, MD5, RSA keySize < 1024, DSA keySize < 1024
 
 #
 # Algorithm restrictions for Secure Socket Layer/Transport Layer Security
@@ -620,8 +622,8 @@
 #
 # Example:
 #   jdk.tls.disabledAlgorithms=MD5, SSLv3, DSA, RSA keySize < 2048
-jdk.tls.disabledAlgorithms=SSLv3, RC4, MD5withRSA, DH keySize < 768, \
-    EC keySize < 224
+jdk.tls.disabledAlgorithms=SSLv3, RC4, MD5withRSA, DH keySize < 1024, \
+    EC keySize < 224, DES40_CBC, RC4_40
 
 # Legacy algorithms for Secure Socket Layer/Transport Layer Security (SSL/TLS)
 # processing in JSSE implementation.
@@ -675,8 +677,6 @@
 #
 jdk.tls.legacyAlgorithms= \
         K_NULL, C_NULL, M_NULL, \
-        DHE_DSS_EXPORT, DHE_RSA_EXPORT, DH_anon_EXPORT, DH_DSS_EXPORT, \
-        DH_RSA_EXPORT, RSA_EXPORT, \
         DH_anon, ECDH_anon, \
         RC4_128, RC4_40, DES_CBC, DES40_CBC, \
         3DES_EDE_CBC
@@ -937,3 +937,24 @@
 #    java.rmi.dgc.VMID;\
 #    java.rmi.dgc.Lease;\
 #    maxdepth=5;maxarray=10000
+
+# CORBA ORBIorTypeCheckRegistryFilter
+# Type check enhancement for ORB::string_to_object processing
+#
+# An IOR type check filter, if configured, is used by an ORB during
+# an ORB::string_to_object invocation to check the veracity of the type encoded
+# in the ior string.
+#
+# The filter pattern consists of a semi-colon separated list of class names.
+# The configured list contains the binary class names of the IDL interface types
+# corresponding to the IDL stub class to be instantiated.
+# As such, a filter specifies a list of IDL stub classes that will be
+# allowed by an ORB when an ORB::string_to_object is invoked.
+# It is used to specify a white list configuration of acceptable
+# IDL stub types which may be contained in a stringified IOR
+# parameter passed as input to an ORB::string_to_object method.
+#
+# Note: This property is currently used by the JDK Reference implementation.
+# It is not guaranteed to be examined and used by other implementations.
+#
+#com.sun.CORBA.ORBIorTypeCheckRegistryFilter=binary_class_name;binary_class_name
--- a/src/share/lib/security/java.security-solaris	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/lib/security/java.security-solaris	Tue Jan 16 22:58:44 2018 -0800
@@ -224,6 +224,7 @@
                jdk.internal.,\
                jdk.nashorn.internal.,\
                jdk.nashorn.tools.,\
+               jdk.xml.internal.,\
                com.sun.activation.registries.
 
 #
@@ -273,6 +274,7 @@
                    jdk.internal.,\
                    jdk.nashorn.internal.,\
                    jdk.nashorn.tools.,\
+                   jdk.xml.internal.,\
                    com.sun.activation.registries.
 
 #
@@ -587,7 +589,7 @@
 #
 # See "jdk.certpath.disabledAlgorithms" for syntax descriptions.
 #
-jdk.jar.disabledAlgorithms=MD2, MD5, RSA keySize < 1024
+jdk.jar.disabledAlgorithms=MD2, MD5, RSA keySize < 1024, DSA keySize < 1024
 
 #
 # Algorithm restrictions for Secure Socket Layer/Transport Layer Security
@@ -619,8 +621,8 @@
 #
 # Example:
 #   jdk.tls.disabledAlgorithms=MD5, SSLv3, DSA, RSA keySize < 2048
-jdk.tls.disabledAlgorithms=SSLv3, RC4, MD5withRSA, DH keySize < 768, \
-    EC keySize < 224
+jdk.tls.disabledAlgorithms=SSLv3, RC4, MD5withRSA, DH keySize < 1024, \
+    EC keySize < 224, DES40_CBC, RC4_40
 
 # Legacy algorithms for Secure Socket Layer/Transport Layer Security (SSL/TLS)
 # processing in JSSE implementation.
@@ -674,8 +676,6 @@
 #
 jdk.tls.legacyAlgorithms= \
         K_NULL, C_NULL, M_NULL, \
-        DHE_DSS_EXPORT, DHE_RSA_EXPORT, DH_anon_EXPORT, DH_DSS_EXPORT, \
-        DH_RSA_EXPORT, RSA_EXPORT, \
         DH_anon, ECDH_anon, \
         RC4_128, RC4_40, DES_CBC, DES40_CBC, \
         3DES_EDE_CBC
@@ -936,3 +936,24 @@
 #    java.rmi.dgc.VMID;\
 #    java.rmi.dgc.Lease;\
 #    maxdepth=5;maxarray=10000
+
+# CORBA ORBIorTypeCheckRegistryFilter
+# Type check enhancement for ORB::string_to_object processing
+#
+# An IOR type check filter, if configured, is used by an ORB during
+# an ORB::string_to_object invocation to check the veracity of the type encoded
+# in the ior string.
+#
+# The filter pattern consists of a semi-colon separated list of class names.
+# The configured list contains the binary class names of the IDL interface types
+# corresponding to the IDL stub class to be instantiated.
+# As such, a filter specifies a list of IDL stub classes that will be
+# allowed by an ORB when an ORB::string_to_object is invoked.
+# It is used to specify a white list configuration of acceptable
+# IDL stub types which may be contained in a stringified IOR
+# parameter passed as input to an ORB::string_to_object method.
+#
+# Note: This property is currently used by the JDK Reference implementation.
+# It is not guaranteed to be examined and used by other implementations.
+#
+#com.sun.CORBA.ORBIorTypeCheckRegistryFilter=binary_class_name;binary_class_name
--- a/src/share/lib/security/java.security-windows	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/lib/security/java.security-windows	Tue Jan 16 22:58:44 2018 -0800
@@ -223,6 +223,7 @@
                jdk.internal.,\
                jdk.nashorn.internal.,\
                jdk.nashorn.tools.,\
+               jdk.xml.internal.,\
                com.sun.activation.registries.,\
                com.sun.java.accessibility.
 
@@ -273,6 +274,7 @@
                    jdk.internal.,\
                    jdk.nashorn.internal.,\
                    jdk.nashorn.tools.,\
+                   jdk.xml.internal.,\
                    com.sun.activation.registries.,\
                    com.sun.java.accessibility.
 
@@ -588,7 +590,7 @@
 #
 # See "jdk.certpath.disabledAlgorithms" for syntax descriptions.
 #
-jdk.jar.disabledAlgorithms=MD2, MD5, RSA keySize < 1024
+jdk.jar.disabledAlgorithms=MD2, MD5, RSA keySize < 1024, DSA keySize < 1024
 
 #
 # Algorithm restrictions for Secure Socket Layer/Transport Layer Security
@@ -620,8 +622,8 @@
 #
 # Example:
 #   jdk.tls.disabledAlgorithms=MD5, SSLv3, DSA, RSA keySize < 2048
-jdk.tls.disabledAlgorithms=SSLv3, RC4, MD5withRSA, DH keySize < 768, \
-    EC keySize < 224
+jdk.tls.disabledAlgorithms=SSLv3, RC4, MD5withRSA, DH keySize < 1024, \
+    EC keySize < 224, DES40_CBC, RC4_40
 
 # Legacy algorithms for Secure Socket Layer/Transport Layer Security (SSL/TLS)
 # processing in JSSE implementation.
@@ -675,8 +677,6 @@
 #
 jdk.tls.legacyAlgorithms= \
         K_NULL, C_NULL, M_NULL, \
-        DHE_DSS_EXPORT, DHE_RSA_EXPORT, DH_anon_EXPORT, DH_DSS_EXPORT, \
-        DH_RSA_EXPORT, RSA_EXPORT, \
         DH_anon, ECDH_anon, \
         RC4_128, RC4_40, DES_CBC, DES40_CBC, \
         3DES_EDE_CBC
@@ -937,3 +937,24 @@
 #    java.rmi.dgc.VMID;\
 #    java.rmi.dgc.Lease;\
 #    maxdepth=5;maxarray=10000
+
+# CORBA ORBIorTypeCheckRegistryFilter
+# Type check enhancement for ORB::string_to_object processing
+#
+# An IOR type check filter, if configured, is used by an ORB during
+# an ORB::string_to_object invocation to check the veracity of the type encoded
+# in the ior string.
+#
+# The filter pattern consists of a semi-colon separated list of class names.
+# The configured list contains the binary class names of the IDL interface types
+# corresponding to the IDL stub class to be instantiated.
+# As such, a filter specifies a list of IDL stub classes that will be
+# allowed by an ORB when an ORB::string_to_object is invoked.
+# It is used to specify a white list configuration of acceptable
+# IDL stub types which may be contained in a stringified IOR
+# parameter passed as input to an ORB::string_to_object method.
+#
+# Note: This property is currently used by the JDK Reference implementation.
+# It is not guaranteed to be examined and used by other implementations.
+#
+#com.sun.CORBA.ORBIorTypeCheckRegistryFilter=binary_class_name;binary_class_name
--- a/src/share/native/sun/font/layout/LookupTables.cpp	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/native/sun/font/layout/LookupTables.cpp	Tue Jan 16 22:58:44 2018 -0800
@@ -52,9 +52,9 @@
 const LookupSegment *BinarySearchLookupTable::lookupSegment(const LETableReference &base, const LookupSegment *segments, LEGlyphID glyph, LEErrorCode &success) const
 {
 
-    le_int16  unity = SWAPW(unitSize);
-    le_int16  probe = SWAPW(searchRange);
-    le_int16  extra = SWAPW(rangeShift);
+    le_uint16  unity = SWAPW(unitSize);
+    le_uint16  probe = SWAPW(searchRange);
+    le_uint16  extra = SWAPW(rangeShift);
     TTGlyphID ttGlyph = (TTGlyphID) LE_GET_GLYPH(glyph);
     LEReferenceTo<LookupSegment> entry(base, success, segments);
     LEReferenceTo<LookupSegment> trial(entry, success, extra);
@@ -84,9 +84,9 @@
 
 const LookupSingle *BinarySearchLookupTable::lookupSingle(const LETableReference &base, const LookupSingle *entries, LEGlyphID glyph, LEErrorCode &success) const
 {
-    le_int16  unity = SWAPW(unitSize);
-    le_int16  probe = SWAPW(searchRange);
-    le_int16  extra = SWAPW(rangeShift);
+    le_uint16  unity = SWAPW(unitSize);
+    le_uint16  probe = SWAPW(searchRange);
+    le_uint16  extra = SWAPW(rangeShift);
     TTGlyphID ttGlyph = (TTGlyphID) LE_GET_GLYPH(glyph);
     LEReferenceTo<LookupSingle> entry(base, success, entries);
     LEReferenceTo<LookupSingle> trial(entry, success, extra);
--- a/src/share/native/sun/font/layout/LookupTables.h	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/native/sun/font/layout/LookupTables.h	Tue Jan 16 22:58:44 2018 -0800
@@ -74,11 +74,11 @@
 
 struct BinarySearchLookupTable : LookupTable
 {
-    le_int16 unitSize;
-    le_int16 nUnits;
-    le_int16 searchRange;
-    le_int16 entrySelector;
-    le_int16 rangeShift;
+    le_uint16 unitSize;
+    le_uint16 nUnits;
+    le_uint16 searchRange;
+    le_uint16 entrySelector;
+    le_uint16 rangeShift;
 
     const LookupSegment *lookupSegment(const LETableReference &base, const LookupSegment *segments, LEGlyphID glyph, LEErrorCode &success) const;
 
--- a/src/share/native/sun/java2d/cmm/lcms/LCMS.c	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/native/sun/java2d/cmm/lcms/LCMS.c	Tue Jan 16 22:58:44 2018 -0800
@@ -644,7 +644,12 @@
 {
     jclass clsLcmsProfile;
     jobject cmmProfile;
-    jfieldID fid = (*env)->GetFieldID (env,
+    jfieldID fid;
+
+    if (pf == NULL) {
+        return NULL;
+    }
+    fid = (*env)->GetFieldID (env,
         (*env)->GetObjectClass(env, pf),
         "cmmProfile", "Lsun/java2d/cmm/Profile;");
     if (fid == NULL) {
--- a/src/share/native/sun/security/jgss/wrapper/GSSLibStub.c	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/native/sun/security/jgss/wrapper/GSSLibStub.c	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2017, 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
@@ -830,7 +830,7 @@
 {
   OM_uint32 minor, major;
   gss_cred_id_t credHdl ;
-  gss_ctx_id_t contextHdl;
+  gss_ctx_id_t contextHdl, contextHdlSave;
   gss_name_t targetName;
   gss_OID mech;
   OM_uint32 flags, aFlags;
@@ -847,7 +847,7 @@
   TRACE0("[GSSLibStub_initContext]");
 
   credHdl = (gss_cred_id_t) jlong_to_ptr(pCred);
-  contextHdl = (gss_ctx_id_t) jlong_to_ptr(
+  contextHdl = contextHdlSave = (gss_ctx_id_t) jlong_to_ptr(
     (*env)->GetLongField(env, jcontextSpi, FID_NativeGSSContext_pContext));
   targetName = (gss_name_t) jlong_to_ptr(pName);
   mech = (gss_OID) jlong_to_ptr((*env)->GetLongField(env, jobj, FID_GSSLibStub_pMech));
@@ -882,10 +882,17 @@
   TRACE2("[GSSLibStub_initContext] after: pContext=%ld, outToken len=%ld",
             (long)contextHdl, (long)outToken.length);
 
+  // update context handle with the latest value if changed
+  // this is to work with both MIT and Solaris. Former deletes half-built
+  // context if error occurs
+  if (contextHdl != contextHdlSave) {
+    (*env)->SetLongField(env, jcontextSpi, FID_NativeGSSContext_pContext,
+                         ptr_to_jlong(contextHdl));
+    TRACE1("[GSSLibStub_initContext] set pContext=%ld", (long)contextHdl);
+  }
+
   if (GSS_ERROR(major) == GSS_S_COMPLETE) {
     /* update member values if needed */
-    (*env)->SetLongField(env, jcontextSpi, FID_NativeGSSContext_pContext,
-                        ptr_to_jlong(contextHdl));
     (*env)->SetIntField(env, jcontextSpi, FID_NativeGSSContext_flags, aFlags);
     TRACE1("[GSSLibStub_initContext] set flags=0x%x", aFlags);
 
@@ -939,7 +946,7 @@
 {
   OM_uint32 minor, major;
   OM_uint32 minor2, major2;
-  gss_ctx_id_t contextHdl;
+  gss_ctx_id_t contextHdl, contextHdlSave;
   gss_cred_id_t credHdl;
   gss_buffer_desc inToken;
   gss_channel_bindings_t cb;
@@ -959,7 +966,7 @@
 
   TRACE0("[GSSLibStub_acceptContext]");
 
-  contextHdl = (gss_ctx_id_t)jlong_to_ptr(
+  contextHdl = contextHdlSave = (gss_ctx_id_t)jlong_to_ptr(
     (*env)->GetLongField(env, jcontextSpi, FID_NativeGSSContext_pContext));
   credHdl = (gss_cred_id_t) jlong_to_ptr(pCred);
   initGSSBuffer(env, jinToken, &inToken);
@@ -996,19 +1003,22 @@
   TRACE3("[GSSLibStub_acceptContext] after: pCred=%ld, pContext=%ld, pDelegCred=%ld",
         (long)credHdl, (long)contextHdl, (long) delCred);
 
+  // update context handle with the latest value if changed
+  // this is to work with both MIT and Solaris. Former deletes half-built
+  // context if error occurs
+  if (contextHdl != contextHdlSave) {
+    (*env)->SetLongField(env, jcontextSpi, FID_NativeGSSContext_pContext,
+                         ptr_to_jlong(contextHdl));
+    TRACE1("[GSSLibStub_acceptContext] set pContext=%ld", (long)contextHdl);
+  }
+
   if (GSS_ERROR(major) == GSS_S_COMPLETE) {
     /* update member values if needed */
-    (*env)->SetLongField(env, jcontextSpi, FID_NativeGSSContext_pContext,
-                        ptr_to_jlong(contextHdl));
-    TRACE1("[GSSLibStub_acceptContext] set pContext=%ld",
-            (long)contextHdl);
-
     // WORKAROUND for a Heimdal bug
     if (delCred == GSS_C_NO_CREDENTIAL) {
         aFlags &= 0xfffffffe;
     }
     (*env)->SetIntField(env, jcontextSpi, FID_NativeGSSContext_flags, aFlags);
-
     TRACE1("[GSSLibStub_acceptContext] set flags=0x%x", aFlags);
 
     if (setTarget) {
--- a/src/share/sample/vm/jvm-clr/invoker.cpp	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/share/sample/vm/jvm-clr/invoker.cpp	Tue Jan 16 22:58:44 2018 -0800
@@ -152,7 +152,7 @@
 
     int nReturn = invokeCLR( wszApplication);
 
-    delete wszApplication;
+    delete[] wszApplication;
 
     return nReturn;
 }
--- a/src/solaris/native/sun/awt/gtk2_interface.c	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/solaris/native/sun/awt/gtk2_interface.c	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2017, 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
@@ -843,46 +843,41 @@
     }
 
     /*
-     * Strip the AT-SPI GTK_MODULEs if present
+     * Strip the AT-SPI GTK_MODULES if present
      */
     gtk_modules_env = getenv ("GTK_MODULES");
+    if ((gtk_modules_env && strstr(gtk_modules_env, "atk-bridge")) ||
+        (gtk_modules_env && strstr(gtk_modules_env, "gail"))) {
+        /* careful, strtok modifies its args */
+        gchar *tmp_env = strdup(gtk_modules_env);
+        if (tmp_env) {
+            /* the new env will be smaller than the old one */
+            gchar *s, *new_env = SAFE_SIZE_STRUCT_ALLOC(malloc,
+                    sizeof(ENV_PREFIX), 1, strlen (gtk_modules_env));
 
-    if (gtk_modules_env && strstr (gtk_modules_env, "atk-bridge") ||
-        gtk_modules_env && strstr (gtk_modules_env, "gail"))
-    {
-        /* the new env will be smaller than the old one */
-        gchar *s, *new_env = SAFE_SIZE_STRUCT_ALLOC(malloc,
-                sizeof(ENV_PREFIX), 1, strlen (gtk_modules_env));
-
-        if (new_env != NULL )
-        {
-            /* careful, strtok modifies its args */
-            gchar *tmp_env = strdup (gtk_modules_env);
-            strcpy(new_env, ENV_PREFIX);
+            if (new_env) {
+                strcpy(new_env, ENV_PREFIX);
 
-            /* strip out 'atk-bridge' and 'gail' */
-            size_t PREFIX_LENGTH = strlen(ENV_PREFIX);
-            while (s = strtok(tmp_env, ":"))
-            {
-                if ((!strstr (s, "atk-bridge")) && (!strstr (s, "gail")))
-                {
-                    if (strlen (new_env) > PREFIX_LENGTH) {
-                        new_env = strcat (new_env, ":");
+                /* strip out 'atk-bridge' and 'gail' */
+                size_t PREFIX_LENGTH = strlen(ENV_PREFIX);
+                gchar *tmp_ptr = NULL;
+                for (s = strtok_r(tmp_env, ":", &tmp_ptr); s;
+                     s = strtok_r(NULL, ":", &tmp_ptr)) {
+                    if ((!strstr(s, "atk-bridge")) && (!strstr(s, "gail"))) {
+                        if (strlen(new_env) > PREFIX_LENGTH) {
+                            new_env = strcat(new_env, ":");
+                        }
+                        new_env = strcat(new_env, s);
                     }
-                    new_env = strcat(new_env, s);
                 }
-                if (tmp_env)
-                {
-                    free (tmp_env);
-                    tmp_env = NULL; /* next call to strtok arg1==NULL */
+                if (putenv(new_env) != 0) {
+                    /* no free() on success, putenv() doesn't copy string */
+                    free(new_env);
                 }
             }
-            putenv (new_env);
-            free (new_env);
-            free (tmp_env);
+            free(tmp_env);
         }
     }
-
     /*
      * GTK should be initialized with gtk_init_check() before use.
      *
--- a/src/windows/native/sun/java2d/d3d/D3DGraphicsDevice.cpp	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/windows/native/sun/java2d/d3d/D3DGraphicsDevice.cpp	Tue Jan 16 22:58:44 2018 -0800
@@ -98,7 +98,7 @@
 
     jstring ret = JNU_NewStringPlatform(env, pAdapterId);
 
-    delete pAdapterId;
+    delete[] pAdapterId;
 
     return ret;
 }
--- a/src/windows/native/sun/windows/WPrinterJob.cpp	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/windows/native/sun/windows/WPrinterJob.cpp	Tue Jan 16 22:58:44 2018 -0800
@@ -508,14 +508,14 @@
           names = env->NewObjectArray(cReturned, cls, NULL);
       }
       if (names == NULL || cls == NULL) {
-          delete buf;
+          delete[] buf;
           return names;
       }
 
       for (int i = 0; i < cReturned; i++) {
           utf_str = JNU_NewStringPlatform(env, buf+(buf_len*i));
             if (utf_str == NULL) {
-                delete buf;
+                delete[] buf;
                 return names;
             }
             env->SetObjectArrayElement(names, i, utf_str);
--- a/src/windows/native/sun/windows/awt_Palette.cpp	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/windows/native/sun/windows/awt_Palette.cpp	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2017, 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
@@ -148,7 +148,7 @@
         pEntry->peFlags = PC_EXPLICIT;
     }
     hPal = ::CreatePalette(pLogPal);
-    delete pLogPal;
+    delete[] pLogPal;
     if ( hPal == 0 ) {
         return 0;
     }
--- a/src/windows/native/sun/windows/awt_Robot.cpp	Mon Jan 08 22:36:23 2018 -0800
+++ b/src/windows/native/sun/windows/awt_Robot.cpp	Tue Jan 16 22:58:44 2018 -0800
@@ -278,7 +278,7 @@
 
     // copy pixels into Java array
     env->SetIntArrayRegion(pixelArray, 0, numPixels, (jint *)pixelData);
-    delete pinfo;
+    delete[] pinfo;
 
     // free all the GDI objects we made
     ::SelectObject(hdcMem, hOldBitmap);
--- a/test/com/sun/crypto/provider/KeyAgreement/DHGenSecretKey.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/test/com/sun/crypto/provider/KeyAgreement/DHGenSecretKey.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2017, 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
@@ -27,6 +27,7 @@
  * @summary Verify that DHKeyAgreement can generate secret key
  * objects for AES algorithm
  * @author Valerie Peng
+ * @run main/othervm -Djdk.crypto.KeyAgreement.legacyKDF=true DHGenSecretKey
  */
 import java.security.*;
 import java.security.interfaces.*;
--- a/test/com/sun/crypto/provider/KeyAgreement/DHKeyAgreement2.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/test/com/sun/crypto/provider/KeyAgreement/DHKeyAgreement2.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, 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
@@ -26,6 +26,7 @@
  * @bug 7146728
  * @summary DHKeyAgreement2
  * @author Jan Luehe
+ * @run main/othervm -Djdk.crypto.KeyAgreement.legacyKDF=true DHKeyAgreement2
  */
 
 import java.io.*;
--- a/test/com/sun/crypto/provider/KeyAgreement/SameDHKeyStressTest.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/test/com/sun/crypto/provider/KeyAgreement/SameDHKeyStressTest.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2017, 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
@@ -26,7 +26,7 @@
  * @bug 8048819
  * @summary This test stressful verifies the assertion of "The secret keys generated
  * by all involved parties should be the same." for javax.crypto.KeyAgreement
- * @run main SameDHKeyStressTest
+ * @run main/othervm -Djdk.crypto.KeyAgreement.legacyKDF=true SameDHKeyStressTest
  */
 import java.security.AlgorithmParameterGenerator;
 import java.security.InvalidAlgorithmParameterException;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/com/sun/crypto/provider/KeyAgreement/SupportedDHKeys.java	Tue Jan 16 22:58:44 2018 -0800
@@ -0,0 +1,110 @@
+/*
+ * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * @test
+ * @bug 8072452
+ * @summary Support DHE sizes up to 8192-bits and DSA sizes up to 3072-bits
+ */
+
+import java.math.BigInteger;
+
+import java.security.*;
+import javax.crypto.*;
+import javax.crypto.interfaces.*;
+import javax.crypto.spec.*;
+
+public class SupportedDHKeys {
+
+    /*
+     * Sizes and values for various lengths.
+     */
+    private enum SupportedKeySize {
+        dhp512(512),   dhp768(768),    dhp832(832),
+        dhp1024(1024), dhp1536(1536),  dhp2048(2048),
+        dhp3072(3072), dhp4096(4096),  dhp6144(6144),
+        dhp8192(8192);
+
+        final int primeSize;
+
+        SupportedKeySize(int primeSize) {
+            this.primeSize = primeSize;
+        }
+    }
+
+    public static void main(String[] args) throws Exception {
+        for (SupportedKeySize keySize : SupportedKeySize.values()) {
+            System.out.println("Checking " + keySize.primeSize + " ...");
+            KeyPairGenerator kpg = KeyPairGenerator.getInstance("DH", "SunJCE");
+            kpg.initialize(keySize.primeSize);
+            KeyPair kp = kpg.generateKeyPair();
+            checkKeyPair(kp, keySize.primeSize);
+
+            DHPublicKey publicKey = (DHPublicKey)kp.getPublic();
+            BigInteger p = publicKey.getParams().getP();
+            BigInteger g = publicKey.getParams().getG();
+            kpg.initialize(new DHParameterSpec(p, g));
+            kp = kpg.generateKeyPair();
+            checkKeyPair(kp, keySize.primeSize);
+        }
+    }
+
+    private static void checkKeyPair(KeyPair kp, int pSize) throws Exception {
+
+        DHPrivateKey privateKey = (DHPrivateKey)kp.getPrivate();
+        BigInteger p = privateKey.getParams().getP();
+        if (p.bitLength() != pSize) {
+            throw new Exception(
+                "Invalid modulus size: " + p.bitLength() + "/" + pSize);
+        }
+
+        // System.out.println("P(" + pSize + "): " + p.toString());
+        if (!p.isProbablePrime(128)) {
+            throw new Exception("Good luck, the modulus is composite!");
+        }
+
+        DHPublicKey publicKey = (DHPublicKey)kp.getPublic();
+        p = publicKey.getParams().getP();
+        if (p.bitLength() != pSize) {
+            throw new Exception(
+                "Invalid modulus size: " + p.bitLength() + "/" + pSize);
+        }
+
+        BigInteger leftOpen = BigInteger.ONE;
+        BigInteger rightOpen = p.subtract(BigInteger.ONE);
+
+        BigInteger x = privateKey.getX();
+        if ((x.compareTo(leftOpen) <= 0) ||
+                (x.compareTo(rightOpen) >= 0)) {
+            throw new Exception(
+                "X outside range [2, p - 2]:  x: " + x + " p: " + p);
+        }
+
+        BigInteger y = publicKey.getY();
+        if ((y.compareTo(leftOpen) <= 0) ||
+                (y.compareTo(rightOpen) >= 0)) {
+            throw new Exception(
+                "Y outside range [2, p - 2]:  x: " + x + " p: " + p);
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/com/sun/crypto/provider/KeyAgreement/SupportedDHParamGens.java	Tue Jan 16 22:58:44 2018 -0800
@@ -0,0 +1,98 @@
+/*
+ * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * @test
+ * @bug 8072452
+ * @summary Support DHE sizes up to 8192-bits and DSA sizes up to 3072-bits
+ * @run main/timeout=300 SupportedDHParamGens 512
+ * @run main/timeout=300 SupportedDHParamGens 768
+ * @run main/timeout=300 SupportedDHParamGens 832
+ * @run main/timeout=300 SupportedDHParamGens 1024
+ * @run main/timeout=600 SupportedDHParamGens 2048
+ * @run main/timeout=700 SupportedDHParamGens 3072
+ */
+
+import java.math.BigInteger;
+
+import java.security.*;
+import javax.crypto.*;
+import javax.crypto.interfaces.*;
+import javax.crypto.spec.*;
+
+public class SupportedDHParamGens {
+
+    public static void main(String[] args) throws Exception {
+        int primeSize = Integer.valueOf(args[0]).intValue();
+
+        System.out.println("Checking " + primeSize + " ...");
+        AlgorithmParameterGenerator apg =
+                AlgorithmParameterGenerator.getInstance("DH", "SunJCE");
+        apg.init(primeSize);
+        AlgorithmParameters ap = apg.generateParameters();
+        DHParameterSpec spec = ap.getParameterSpec(DHParameterSpec.class);
+
+        KeyPairGenerator kpg = KeyPairGenerator.getInstance("DH", "SunJCE");
+        kpg.initialize(spec);
+        KeyPair kp = kpg.generateKeyPair();
+        checkKeyPair(kp, primeSize);
+    }
+
+    private static void checkKeyPair(KeyPair kp, int pSize) throws Exception {
+
+        DHPrivateKey privateKey = (DHPrivateKey)kp.getPrivate();
+        BigInteger p = privateKey.getParams().getP();
+        if (p.bitLength() != pSize) {
+            throw new Exception(
+                "Invalid modulus size: " + p.bitLength() + "/" + pSize);
+        }
+
+        if (!p.isProbablePrime(128)) {
+            throw new Exception("Good luck, the modulus is composite!");
+        }
+
+        DHPublicKey publicKey = (DHPublicKey)kp.getPublic();
+        p = publicKey.getParams().getP();
+        if (p.bitLength() != pSize) {
+            throw new Exception(
+                "Invalid modulus size: " + p.bitLength() + "/" + pSize);
+        }
+
+        BigInteger leftOpen = BigInteger.ONE;
+        BigInteger rightOpen = p.subtract(BigInteger.ONE);
+
+        BigInteger x = privateKey.getX();
+        if ((x.compareTo(leftOpen) <= 0) ||
+                (x.compareTo(rightOpen) >= 0)) {
+            throw new Exception(
+                "X outside range [2, p - 2]:  x: " + x + " p: " + p);
+        }
+
+        BigInteger y = publicKey.getY();
+        if ((y.compareTo(leftOpen) <= 0) ||
+                (y.compareTo(rightOpen) >= 0)) {
+            throw new Exception(
+                "Y outside range [2, p - 2]:  x: " + x + " p: " + p);
+        }
+    }
+}
--- a/test/com/sun/crypto/provider/KeyAgreement/TestExponentSize.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/test/com/sun/crypto/provider/KeyAgreement/TestExponentSize.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2017, 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
@@ -83,10 +83,10 @@
         KeyPair kp;
         KeyPairGenerator kpg = KeyPairGenerator.getInstance("DH", "SunJCE");
 
-        // Sun's default uses a default psize of 1024 and
+        // Sun's default uses a default psize of 2048 and
         // lsize of (pSize / 2) but at least 384 bits
         kp = kpg.generateKeyPair();
-        checkKeyPair(kp, Sizes.ten24, Sizes.five12);
+        checkKeyPair(kp, Sizes.twenty48, Sizes.ten24);
 
         DHPublicKey publicKey = (DHPublicKey)kp.getPublic();
         BigInteger p = publicKey.getParams().getP();
@@ -98,15 +98,15 @@
 
         kpg.initialize(new DHParameterSpec(p, g, Sizes.ten24.getIntSize()));
         kp = kpg.generateKeyPair();
-        checkKeyPair(kp, Sizes.ten24, Sizes.ten24);
+        checkKeyPair(kp, Sizes.twenty48, Sizes.ten24);
 
         kpg.initialize(new DHParameterSpec(p, g, Sizes.five12.getIntSize()));
         kp = kpg.generateKeyPair();
-        checkKeyPair(kp, Sizes.ten24, Sizes.five12);
+        checkKeyPair(kp, Sizes.twenty48, Sizes.five12);
 
         kpg.initialize(new DHParameterSpec(p, g, Sizes.two56.getIntSize()));
         kp = kpg.generateKeyPair();
-        checkKeyPair(kp, Sizes.ten24, Sizes.two56);
+        checkKeyPair(kp, Sizes.twenty48, Sizes.two56);
 
         kpg.initialize(Sizes.five12.getIntSize());
         kp = kpg.generateKeyPair();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/com/sun/crypto/provider/KeyAgreement/UnsupportedDHKeys.java	Tue Jan 16 22:58:44 2018 -0800
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * @test
+ * @bug 8072452
+ * @summary Support DHE sizes up to 8192-bits and DSA sizes up to 3072-bits
+ */
+
+import java.math.BigInteger;
+
+import java.security.*;
+import javax.crypto.*;
+import javax.crypto.interfaces.*;
+import javax.crypto.spec.*;
+
+public class UnsupportedDHKeys {
+
+    /*
+     * Sizes and values for various lengths.
+     */
+    private enum UnsupportedKeySize {
+        // not multiple of 64
+        dhp513(513),    dhp769(769),    dhp895(895),
+        dhp1023(1023),  dhp1535(1535),  dhp2047(2047),
+
+        // unsupported
+        dhp2176(2176),  dhp3008(3008),  dhp4032(4032),
+        dhp5120(5120),  dhp6400(6400),  dhp7680(7680),
+        dhp8191(8191),  dhp8128(8128),  dhp8260(8260);
+
+        final int primeSize;
+
+        UnsupportedKeySize(int primeSize) {
+            this.primeSize = primeSize;
+        }
+    }
+
+    public static void main(String[] args) throws Exception {
+        for (UnsupportedKeySize keySize : UnsupportedKeySize.values()) {
+            try {
+                System.out.println("Checking " + keySize.primeSize + " ...");
+                KeyPairGenerator kpg =
+                        KeyPairGenerator.getInstance("DH", "SunJCE");
+                kpg.initialize(keySize.primeSize);
+
+                throw new Exception("Should not support " + keySize.primeSize);
+            } catch (InvalidParameterException ipe) {
+                System.out.println("\tOk, unsupported");
+            }
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/com/sun/jndi/dns/Parser.java	Tue Jan 16 22:58:44 2018 -0800
@@ -0,0 +1,143 @@
+/*
+ * Copyright (c) 2014, Red Hat, Inc.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8035105
+ * @summary DNS resource record parsing
+ */
+
+import com.sun.jndi.dns.ResourceRecord;
+import javax.naming.CommunicationException;
+import javax.naming.InvalidNameException;;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+
+import java.io.IOException;
+
+import static java.nio.charset.StandardCharsets.ISO_8859_1;
+
+public class Parser {
+    static Constructor<ResourceRecord> rrConstructor;
+    static {
+        try {
+            rrConstructor = ResourceRecord.class.getDeclaredConstructor(
+                byte[].class, int.class, int.class, boolean.class,
+                boolean.class);
+            rrConstructor.setAccessible(true);
+        } catch (Exception e) {
+            throw new AssertionError(e);
+        }
+    }
+
+    static ResourceRecord parse(String data, int offset, boolean qSection)
+        throws Throwable {
+        byte[] bytes = data.getBytes(ISO_8859_1);
+        try {
+            return rrConstructor.newInstance(
+                bytes, bytes.length, offset, qSection, !qSection);
+        } catch (InvocationTargetException e) {
+            throw e.getCause();
+        }
+    }
+
+    public static void main(String[] args) throws Throwable {
+        ResourceRecord rr;
+
+        rr = parse("\003www\007example\003com\000\000\002\000\001",
+            0, true);
+        if (!rr.getName().toString().equals("www.example.com."))
+            throw new AssertionError(rr.getName().toString());
+        if (rr.getRrclass() != 1)
+            throw new AssertionError("RCLASS: " + rr.getRrclass());
+        if (rr.getType() != 2)
+            throw new AssertionError("RTYPE: " + rr.getType());
+
+        String longLabel = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" +
+            "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
+
+        rr = parse("\077" + longLabel + "\077" + longLabel +
+            "\077" + longLabel + "\061" + longLabel.substring(0, 49) +
+            "\007example\003com\000\000\002\000\001",
+             0, true);
+        if (!rr.getName().toString().equals(longLabel +
+            '.' + longLabel + '.' + longLabel +
+            '.' + longLabel.substring(0, 49) + ".example.com."))
+            throw new AssertionError(rr.getName().toString());
+        if (rr.getRrclass() != 1)
+            throw new AssertionError("RCLASS: " + rr.getRrclass());
+        if (rr.getType() != 2)
+            throw new AssertionError("RTYPE: " + rr.getType());
+
+        rr = parse("1-2-3-4-5-6-" +
+            "\003www\007example\003com\000\000\002\000\001" +
+            "\300\014\000\002\000\001\000\001\121\200" +
+            "\000\005\002ns\300\020",
+            33, false);
+        if (!rr.getName().toString().equals("www.example.com."))
+            throw new AssertionError(rr.getName().toString());
+        if (rr.getRrclass() != 1)
+            throw new AssertionError("RCLASS: " + rr.getRrclass());
+        if (rr.getType() != 2)
+            throw new AssertionError("RTYPE: " + rr.getType());
+        if (!rr.getRdata().toString().equals("ns.example.com."))
+            throw new AssertionError("RDATA: " + rr.getRdata());
+
+        try {
+            parse("1-2-3-4-5-6-" +
+                "\003www\007example\003com\000\000\002\000\001" +
+                "\300\014\000\002\000\001\300\051\300\047" +
+                "\000\005\002ns\300\051",
+                33, false);
+            throw new AssertionError();
+        } catch (CommunicationException e) {
+            if (!e.getMessage().equals("DNS error: malformed packet")
+                || e.getCause().getClass() != IOException.class
+                || !e.getCause().getMessage().equals(
+                    "Too many compression references"))
+                throw e;
+        }
+
+        try {
+            String longLabel62 = "\076" + longLabel.substring(1);
+            parse(longLabel62 + longLabel62 + longLabel62 + longLabel62 +
+                "\002XX\000\000\002\000\001", 0, true);
+            throw new AssertionError();
+        } catch (CommunicationException e) {
+            if (!e.getMessage().equals("DNS error: malformed packet")
+                || e.getCause().getClass() != InvalidNameException.class
+                || !e.getCause().getMessage().equals("Name too long"))
+                throw e;
+        }
+        try {
+            parse("\100Y" + longLabel + "\000\000\002\000\001", 0, true);
+            throw new AssertionError();
+        } catch (CommunicationException e) {
+            if (!e.getMessage().equals("DNS error: malformed packet")
+                || e.getCause().getClass() != IOException.class
+                || !e.getCause().getMessage().equals("Invalid label type: 64"))
+                throw e;
+        }
+    }
+}
--- a/test/java/lang/SecurityManager/CheckPackageAccess.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/test/java/lang/SecurityManager/CheckPackageAccess.java	Tue Jan 16 22:58:44 2018 -0800
@@ -24,6 +24,7 @@
 /*
  *  @test
  *  @bug 6741606 7146431 8000450 8019830 8022945 8027144 8041633 8179423
+ *       8186080
  *  @summary Make sure all restricted packages listed in the package.access
  *           property in the java.security file are blocked
  *  @run main/othervm CheckPackageAccess
@@ -87,6 +88,7 @@
         "jdk.internal.",
         "jdk.nashorn.internal.",
         "jdk.nashorn.tools.",
+        "jdk.xml.internal.",
         "com.sun.activation.registries."
     };
 
--- a/test/java/rmi/testlibrary/TestSocketFactory.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/test/java/rmi/testlibrary/TestSocketFactory.java	Tue Jan 16 22:58:44 2018 -0800
@@ -45,20 +45,43 @@
 import java.util.Set;
 
 import org.testng.Assert;
-import org.testng.TestNG;
 import org.testng.annotations.Test;
 import org.testng.annotations.DataProvider;
 
+/*
+ * @test
+ * @summary TestSocket Factory and tests of the basic trigger, match, and replace functions
+ * @run testng TestSocketFactory
+ * @bug 8186539
+ */
 
 /**
  * A RMISocketFactory utility factory to log RMI stream contents and to
- * match and replace output stream contents to simulate failures.
+ * trigger, and then match and replace output stream contents to simulate failures.
+ * <p>
+ * The trigger is a sequence of bytes that must be found before looking
+ * for the bytes to match and replace.  If the trigger sequence is empty
+ * matching is immediately enabled. While waiting for the trigger to be found
+ * bytes written to the streams are written through to the output stream.
+ * The when triggered and when a trigger is non-empty, matching looks for
+ * the sequence of bytes supplied.  If the sequence is empty, no matching or
+ * replacement is performed.
+ * While waiting for a complete match, the partial matched bytes are not
+ * written to the output stream.  When the match is incomplete, the partial
+ * matched bytes are written to the output.  When a match is complete the
+ * full replacement byte array is written to the output.
+ * <p>
+ * The trigger, match, and replacement bytes arrays can be changed at any
+ * time and immediately reset and restart matching.  Changes are propagated
+ * to all of the sockets created from the factories immediately.
  */
 public class TestSocketFactory extends RMISocketFactory
         implements RMIClientSocketFactory, RMIServerSocketFactory, Serializable {
 
     private static final long serialVersionUID = 1L;
 
+    private volatile transient byte[] triggerBytes;
+
     private volatile transient byte[] matchBytes;
 
     private volatile transient byte[] replaceBytes;
@@ -67,6 +90,8 @@
 
     private transient final List<InterposeServerSocket> serverSockets = new ArrayList<>();
 
+    static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
+
     public static final boolean DEBUG = false;
 
     /**
@@ -82,28 +107,51 @@
     }
 
     /**
-     * Create a socket factory that creates InputStreams that log
-     * and OutputStreams that log .
+     * Create a socket factory that creates InputStreams
+     * and OutputStreams that log.
      */
     public TestSocketFactory() {
-        this.matchBytes = new byte[0];
-        this.replaceBytes = this.matchBytes;
-        System.out.printf("Creating TestSocketFactory()%n");
+        this.triggerBytes = EMPTY_BYTE_ARRAY;
+        this.matchBytes = EMPTY_BYTE_ARRAY;
+        this.replaceBytes = EMPTY_BYTE_ARRAY;
+    }
+
+    /**
+     * Set the match and replacement bytes, with an empty trigger.
+     * The match and replacements are propagated to all existing sockets.
+     *
+     * @param matchBytes bytes to match
+     * @param replaceBytes bytes to replace the matched bytes
+     */
+    public void setMatchReplaceBytes(byte[] matchBytes, byte[] replaceBytes) {
+        setMatchReplaceBytes(EMPTY_BYTE_ARRAY, matchBytes, replaceBytes);
     }
 
-    public void setMatchReplaceBytes(byte[] matchBytes, byte[] replaceBytes) {
+    /**
+     * Set the trigger, match, and replacement bytes.
+     * The trigger, match, and replacements are propagated to all existing sockets.
+     *
+     * @param triggerBytes array of bytes to use as a trigger, may be zero length
+     * @param matchBytes bytes to match after the trigger has been seen
+     * @param replaceBytes bytes to replace the matched bytes
+     */
+    public void setMatchReplaceBytes(byte[] triggerBytes, byte[] matchBytes,
+                                     byte[] replaceBytes) {
+        this.triggerBytes = Objects.requireNonNull(triggerBytes, "triggerBytes");
         this.matchBytes = Objects.requireNonNull(matchBytes, "matchBytes");
         this.replaceBytes = Objects.requireNonNull(replaceBytes, "replaceBytes");
-        sockets.forEach( s -> s.setMatchReplaceBytes(matchBytes, replaceBytes));
-        serverSockets.forEach( s -> s.setMatchReplaceBytes(matchBytes, replaceBytes));
-
+        sockets.forEach( s -> s.setMatchReplaceBytes(triggerBytes, matchBytes,
+                replaceBytes));
+        serverSockets.forEach( s -> s.setMatchReplaceBytes(triggerBytes, matchBytes,
+                replaceBytes));
     }
 
     @Override
     public Socket createSocket(String host, int port) throws IOException {
         Socket socket = RMISocketFactory.getDefaultSocketFactory()
                 .createSocket(host, port);
-        InterposeSocket s = new InterposeSocket(socket, matchBytes, replaceBytes);
+        InterposeSocket s = new InterposeSocket(socket,
+                triggerBytes, matchBytes, replaceBytes);
         sockets.add(s);
         return s;
     }
@@ -122,7 +170,8 @@
 
         ServerSocket serverSocket = RMISocketFactory.getDefaultSocketFactory()
                 .createServerSocket(port);
-        InterposeServerSocket ss = new InterposeServerSocket(serverSocket, matchBytes, replaceBytes);
+        InterposeServerSocket ss = new InterposeServerSocket(serverSocket,
+                triggerBytes, matchBytes, replaceBytes);
         serverSockets.add(ss);
         return ss;
     }
@@ -139,13 +188,15 @@
     /**
      * An InterposeSocket wraps a socket that produces InputStreams
      * and OutputStreams that log the traffic.
-     * The OutputStreams it produces match an array of bytes and replace them.
+     * The OutputStreams it produces watch for a trigger and then
+     * match an array of bytes and replace them.
      * Useful for injecting protocol and content errors.
      */
     public static class InterposeSocket extends Socket {
         private final Socket socket;
         private InputStream in;
         private MatchReplaceOutputStream out;
+        private volatile byte[] triggerBytes;
         private volatile byte[] matchBytes;
         private volatile byte[] replaceBytes;
         private final ByteArrayOutputStream inLogStream;
@@ -153,8 +204,28 @@
         private final String name;
         private static volatile int num = 0;    // index for created InterposeSockets
 
+        /**
+         * Construct a socket that interposes on a socket to match and replace.
+         * The trigger is empty.
+         * @param socket the underlying socket
+         * @param matchBytes the bytes that must match
+         * @param replaceBytes the replacement bytes
+         */
         public InterposeSocket(Socket socket, byte[] matchBytes, byte[] replaceBytes) {
+            this(socket, EMPTY_BYTE_ARRAY, matchBytes, replaceBytes);
+        }
+
+        /**
+         * Construct a socket that interposes on a socket to match and replace.
+         * @param socket the underlying socket
+         * @param triggerBytes array of bytes to enable matching
+         * @param matchBytes the bytes that must match
+         * @param replaceBytes the replacement bytes
+         */
+        public InterposeSocket(Socket socket, byte[]
+                triggerBytes, byte[] matchBytes, byte[] replaceBytes) {
             this.socket = socket;
+            this.triggerBytes = Objects.requireNonNull(triggerBytes, "triggerBytes");
             this.matchBytes = Objects.requireNonNull(matchBytes, "matchBytes");
             this.replaceBytes = Objects.requireNonNull(replaceBytes, "replaceBytes");
             this.inLogStream = new ByteArrayOutputStream();
@@ -164,10 +235,32 @@
                     + socket.getLocalPort() + " <  " + socket.getPort();
         }
 
+        /**
+         * Set the match and replacement bytes, with an empty trigger.
+         * The match and replacements are propagated to all existing sockets.
+         *
+         * @param matchBytes bytes to match
+         * @param replaceBytes bytes to replace the matched bytes
+         */
         public void setMatchReplaceBytes(byte[] matchBytes, byte[] replaceBytes) {
+            this.setMatchReplaceBytes(EMPTY_BYTE_ARRAY, matchBytes, replaceBytes);
+        }
+
+        /**
+         * Set the trigger, match, and replacement bytes.
+         * The trigger, match, and replacements are propagated to the
+         * MatchReplaceOutputStream.
+         *
+         * @param triggerBytes array of bytes to use as a trigger, may be zero length
+         * @param matchBytes bytes to match after the trigger has been seen
+         * @param replaceBytes bytes to replace the matched bytes
+         */
+        public void setMatchReplaceBytes(byte[] triggerBytes, byte[] matchBytes,
+                                         byte[] replaceBytes) {
+            this.triggerBytes = triggerBytes;
             this.matchBytes = matchBytes;
             this.replaceBytes = replaceBytes;
-            out.setMatchReplaceBytes(matchBytes, replaceBytes);
+            out.setMatchReplaceBytes(triggerBytes, matchBytes, replaceBytes);
         }
 
         @Override
@@ -263,7 +356,8 @@
                 OutputStream o = socket.getOutputStream();
                 String name = Thread.currentThread().getName() + ": "
                         + socket.getLocalPort() + "  > " + socket.getPort();
-                out = new MatchReplaceOutputStream(o, name, outLogStream, matchBytes, replaceBytes);
+                out = new MatchReplaceOutputStream(o, name, outLogStream,
+                        triggerBytes, matchBytes, replaceBytes);
                 DEBUG("Created new MatchReplaceOutputStream: %s%n", name);
             }
             return out;
@@ -293,20 +387,63 @@
      */
     public static class InterposeServerSocket extends ServerSocket {
         private final ServerSocket socket;
+        private volatile byte[] triggerBytes;
         private volatile byte[] matchBytes;
         private volatile byte[] replaceBytes;
         private final List<InterposeSocket> sockets = new ArrayList<>();
 
-        public InterposeServerSocket(ServerSocket socket, byte[] matchBytes, byte[] replaceBytes) throws IOException {
+        /**
+         * Construct a server socket that interposes on a socket to match and replace.
+         * The trigger is empty.
+         * @param socket the underlying socket
+         * @param matchBytes the bytes that must match
+         * @param replaceBytes the replacement bytes
+         */
+        public InterposeServerSocket(ServerSocket socket, byte[] matchBytes,
+                                     byte[] replaceBytes) throws IOException {
+            this(socket, EMPTY_BYTE_ARRAY, matchBytes, replaceBytes);
+        }
+
+        /**
+         * Construct a server socket that interposes on a socket to match and replace.
+         * @param socket the underlying socket
+         * @param triggerBytes array of bytes to enable matching
+         * @param matchBytes the bytes that must match
+         * @param replaceBytes the replacement bytes
+         */
+        public InterposeServerSocket(ServerSocket socket, byte[] triggerBytes,
+                                     byte[] matchBytes, byte[] replaceBytes) throws IOException {
             this.socket = socket;
+            this.triggerBytes = Objects.requireNonNull(triggerBytes, "triggerBytes");
             this.matchBytes = Objects.requireNonNull(matchBytes, "matchBytes");
             this.replaceBytes = Objects.requireNonNull(replaceBytes, "replaceBytes");
         }
 
+        /**
+         * Set the match and replacement bytes, with an empty trigger.
+         * The match and replacements are propagated to all existing sockets.
+         *
+         * @param matchBytes bytes to match
+         * @param replaceBytes bytes to replace the matched bytes
+         */
         public void setMatchReplaceBytes(byte[] matchBytes, byte[] replaceBytes) {
+            setMatchReplaceBytes(EMPTY_BYTE_ARRAY, matchBytes, replaceBytes);
+        }
+
+        /**
+         * Set the trigger, match, and replacement bytes.
+         * The trigger, match, and replacements are propagated to all existing sockets.
+         *
+         * @param triggerBytes array of bytes to use as a trigger, may be zero length
+         * @param matchBytes bytes to match after the trigger has been seen
+         * @param replaceBytes bytes to replace the matched bytes
+         */
+        public void setMatchReplaceBytes(byte[] triggerBytes, byte[] matchBytes,
+                                         byte[] replaceBytes) {
+            this.triggerBytes = triggerBytes;
             this.matchBytes = matchBytes;
             this.replaceBytes = replaceBytes;
-            sockets.forEach(s -> s.setMatchReplaceBytes(matchBytes, replaceBytes));
+            sockets.forEach(s -> s.setMatchReplaceBytes(triggerBytes, matchBytes, replaceBytes));
         }
         /**
          * Return a snapshot of the current list of sockets created from this server socket.
@@ -433,22 +570,33 @@
     }
 
     /**
-     * An OutputStream that replaces one string of bytes with another.
+     * An OutputStream that looks for a trigger to enable matching and
+     * replaces one string of bytes with another.
      * If any range matches, the match starts after the partial match.
      */
     static class MatchReplaceOutputStream extends OutputStream {
         private final OutputStream out;
         private final String name;
+        private volatile byte[] triggerBytes;
         private volatile byte[] matchBytes;
         private volatile byte[] replaceBytes;
+        int triggerIndex;
         int matchIndex;
         private int bytesOut = 0;
         private final OutputStream log;
 
         MatchReplaceOutputStream(OutputStream out, String name, OutputStream log,
                                  byte[] matchBytes, byte[] replaceBytes) {
+            this(out, name, log, EMPTY_BYTE_ARRAY, matchBytes, replaceBytes);
+        }
+
+        MatchReplaceOutputStream(OutputStream out, String name, OutputStream log,
+                                 byte[] triggerBytes, byte[] matchBytes,
+                                 byte[] replaceBytes) {
             this.out = out;
             this.name = name;
+            this.triggerBytes = Objects.requireNonNull(triggerBytes, "triggerBytes");
+            triggerIndex = 0;
             this.matchBytes = Objects.requireNonNull(matchBytes, "matchBytes");
             this.replaceBytes = Objects.requireNonNull(replaceBytes, "replaceBytes");
             matchIndex = 0;
@@ -456,8 +604,15 @@
         }
 
         public void setMatchReplaceBytes(byte[] matchBytes, byte[] replaceBytes) {
-            this.matchBytes = matchBytes;
-            this.replaceBytes = replaceBytes;
+            setMatchReplaceBytes(EMPTY_BYTE_ARRAY, matchBytes, replaceBytes);
+        }
+
+        public void setMatchReplaceBytes(byte[] triggerBytes, byte[] matchBytes,
+                                         byte[] replaceBytes) {
+            this.triggerBytes = Objects.requireNonNull(triggerBytes, "triggerBytes");
+            triggerIndex = 0;
+            this.matchBytes = Objects.requireNonNull(matchBytes, "matchBytes");
+            this.replaceBytes = Objects.requireNonNull(replaceBytes, "replaceBytes");
             matchIndex = 0;
         }
 
@@ -465,38 +620,65 @@
         public void write(int b) throws IOException {
             b = b & 0xff;
             if (matchBytes.length == 0) {
+                // fast path, no match
                 out.write(b);
                 log.write(b);
                 bytesOut++;
                 return;
             }
-            if (b == (matchBytes[matchIndex] & 0xff)) {
-                if (++matchIndex >= matchBytes.length) {
-                    matchIndex = 0;
-                    DEBUG( "TestSocketFactory MatchReplace %s replaced %d bytes at offset: %d (x%04x)%n",
-                            name, replaceBytes.length, bytesOut, bytesOut);
-                    out.write(replaceBytes);
-                    log.write(replaceBytes);
-                    bytesOut += replaceBytes.length;
-                }
+            // if trigger not satisfied, keep looking
+            if (triggerBytes.length != 0 && triggerIndex < triggerBytes.length) {
+                out.write(b);
+                log.write(b);
+                bytesOut++;
+
+                triggerIndex = (b == (triggerBytes[triggerIndex] & 0xff))
+                        ? ++triggerIndex    // matching advance
+                        : 0;
             } else {
-                if (matchIndex > 0) {
-                    // mismatch, write out any that matched already
-                    if (matchIndex > 0) // Only non-trivial matches
-                        DEBUG( "Partial match %s matched %d bytes at offset: %d (0x%04x), expected: x%02x, actual: x%02x%n",
-                                name, matchIndex, bytesOut, bytesOut,  matchBytes[matchIndex], b);
-                    out.write(matchBytes, 0, matchIndex);
-                    log.write(matchBytes, 0, matchIndex);
-                    bytesOut += matchIndex;
-                    matchIndex = 0;
+                // trigger not used or has been satisfied
+                if (b == (matchBytes[matchIndex] & 0xff)) {
+                    if (++matchIndex >= matchBytes.length) {
+                        matchIndex = 0;
+                        triggerIndex = 0;       // match/replace ok, reset trigger
+                        DEBUG("TestSocketFactory MatchReplace %s replaced %d bytes " +
+                                "at offset: %d (x%04x)%n",
+                                name, replaceBytes.length, bytesOut, bytesOut);
+                        out.write(replaceBytes);
+                        log.write(replaceBytes);
+                        bytesOut += replaceBytes.length;
+                    }
+                } else {
+                    if (matchIndex > 0) {
+                        // mismatch, write out any that matched already
+                        DEBUG("Partial match %s matched %d bytes at offset: %d (0x%04x), expected: x%02x, actual: x%02x%n",
+                            name, matchIndex, bytesOut, bytesOut, matchBytes[matchIndex], b);
+                        out.write(matchBytes, 0, matchIndex);
+                        log.write(matchBytes, 0, matchIndex);
+                        bytesOut += matchIndex;
+                        matchIndex = 0;
+                    }
+                    if (b == (matchBytes[matchIndex] & 0xff)) {
+                        matchIndex++;
+                    } else {
+                        out.write(b);
+                        log.write(b);
+                        bytesOut++;
+                    }
                 }
-                if (b == (matchBytes[matchIndex] & 0xff)) {
-                    matchIndex++;
-                } else {
-                    out.write(b);
-                    log.write(b);
-                    bytesOut++;
-                }
+            }
+        }
+
+        public void flush() throws IOException {
+            if (matchIndex > 0) {
+                // write out any that matched already to avoid consumer hang.
+                // Match/replace across a flush is not supported.
+                DEBUG( "Flush partial match %s matched %d bytes at offset: %d (0x%04x)%n",
+                        name, matchIndex, bytesOut, bytesOut);
+                out.write(matchBytes, 0, matchIndex);
+                log.write(matchBytes, 0, matchIndex);
+                bytesOut += matchIndex;
+                matchIndex = 0;
             }
         }
 
@@ -506,18 +688,44 @@
         }
     }
 
-    private static byte[] orig = new byte[]{
+    private static byte[] obj1Data = new byte[] {
+            0x7e, 0x7e, 0x7e,
             (byte) 0x80, 0x05,
-            0x73, 0x72, 0x00, 0x12, // TC_OBJECT, TC_CLASSDESC, length = 18
-            0x6A, 0x61, 0x76, 0x61, 0x2E, 0x72, 0x6D, 0x69, 0x2E, // "java.rmi."
-            0x64, 0x67, 0x63, 0x2E, 0x4C, 0x65, 0x61, 0x73, 0x65  // "dgc.Lease"
+            0x7f, 0x7f, 0x7f,
+            0x73, 0x72, 0x00, 0x10, // TC_OBJECT, TC_CLASSDESC, length = 16
+            (byte)'j', (byte)'a', (byte)'v', (byte)'a', (byte)'.',
+            (byte)'l', (byte)'a', (byte)'n', (byte)'g', (byte)'.',
+            (byte)'n', (byte)'u', (byte)'m', (byte)'b', (byte)'e', (byte)'r'
+    };
+    private static byte[] obj1Result = new byte[] {
+            0x7e, 0x7e, 0x7e,
+            (byte) 0x80, 0x05,
+            0x7f, 0x7f, 0x7f,
+            0x73, 0x72, 0x00, 0x11, // TC_OBJECT, TC_CLASSDESC, length = 17
+            (byte)'j', (byte)'a', (byte)'v', (byte)'a', (byte)'.',
+            (byte)'l', (byte)'a', (byte)'n', (byte)'g', (byte)'.',
+            (byte)'I', (byte)'n', (byte)'t', (byte)'e', (byte)'g', (byte)'e', (byte)'r'
     };
-    private static byte[] repl = new byte[]{
-            (byte) 0x80, 0x05,
-            0x73, 0x72, 0x00, 0x12, // TC_OBJECT, TC_CLASSDESC, length = 18
-            0x6A, 0x61, 0x76, 0x61, 0x2E, (byte) 'l', (byte) 'a', (byte) 'n', (byte) 'g',
-            0x2E, (byte) 'R', (byte) 'u', (byte) 'n', (byte) 'n', (byte) 'a', (byte) 'b', (byte) 'l',
-            (byte) 'e'
+    private static byte[] obj1Trigger = new byte[] {
+            (byte) 0x80, 0x05
+    };
+    private static byte[] obj1Trigger2 = new byte[] {
+            0x7D, 0x7D, 0x7D, 0x7D,
+    };
+    private static byte[] obj1Trigger3 = new byte[] {
+            0x7F,
+    };
+    private static byte[] obj1Match = new byte[] {
+            0x73, 0x72, 0x00, 0x10, // TC_OBJECT, TC_CLASSDESC, length = 16
+            (byte)'j', (byte)'a', (byte)'v', (byte)'a', (byte)'.',
+            (byte)'l', (byte)'a', (byte)'n', (byte)'g', (byte)'.',
+            (byte)'n', (byte)'u', (byte)'m', (byte)'b', (byte)'e', (byte)'r'
+    };
+    private static byte[] obj1Repl = new byte[] {
+            0x73, 0x72, 0x00, 0x11, // TC_OBJECT, TC_CLASSDESC, length = 17
+            (byte)'j', (byte)'a', (byte)'v', (byte)'a', (byte)'.',
+            (byte)'l', (byte)'a', (byte)'n', (byte)'g', (byte)'.',
+            (byte)'I', (byte)'n', (byte)'t', (byte)'e', (byte)'g', (byte)'e', (byte)'r'
     };
 
     @DataProvider(name = "MatchReplaceData")
@@ -532,26 +740,42 @@
         byte[] bytes6 = new byte[]{1, 2, 0x10, 0x20, 0x30};
 
         return new Object[][]{
-                {new byte[]{}, new byte[]{}, empty, empty},
-                {new byte[]{}, new byte[]{}, byte1, byte1},
-                {new byte[]{3, 4}, new byte[]{4, 3}, byte1, bytes2}, //swap bytes
-                {new byte[]{3, 4}, new byte[]{0x10, 0x20, 0x30, 0x40}, byte1, bytes4}, // insert
-                {new byte[]{1, 2, 0x10, 0x20}, new byte[]{}, bytes4, bytes5}, // delete head
-                {new byte[]{0x40, 5, 6}, new byte[]{}, bytes4, bytes6},   // delete tail
-                {new byte[]{0x40, 0x50}, new byte[]{0x60, 0x50}, bytes4, bytes4}, // partial match, replace nothing
-                {bytes4a, bytes3, bytes4, bytes4}, // long partial match, not replaced
-                {orig, repl, orig, repl},
+                {EMPTY_BYTE_ARRAY, new byte[]{}, new byte[]{},
+                        empty, empty},
+                {EMPTY_BYTE_ARRAY, new byte[]{}, new byte[]{},
+                        byte1, byte1},
+                {EMPTY_BYTE_ARRAY, new byte[]{3, 4}, new byte[]{4, 3},
+                        byte1, bytes2}, //swap bytes
+                {EMPTY_BYTE_ARRAY, new byte[]{3, 4}, new byte[]{0x10, 0x20, 0x30, 0x40},
+                        byte1, bytes4}, // insert
+                {EMPTY_BYTE_ARRAY, new byte[]{1, 2, 0x10, 0x20}, new byte[]{},
+                        bytes4, bytes5}, // delete head
+                {EMPTY_BYTE_ARRAY, new byte[]{0x40, 5, 6}, new byte[]{},
+                        bytes4, bytes6},   // delete tail
+                {EMPTY_BYTE_ARRAY, new byte[]{0x40, 0x50}, new byte[]{0x60, 0x50},
+                        bytes4, bytes4}, // partial match, replace nothing
+                {EMPTY_BYTE_ARRAY, bytes4a, bytes3,
+                        bytes4, bytes4}, // long partial match, not replaced
+                {EMPTY_BYTE_ARRAY, obj1Match, obj1Repl,
+                        obj1Match, obj1Repl},
+                {obj1Trigger, obj1Match, obj1Repl,
+                        obj1Data, obj1Result},
+                {obj1Trigger3, obj1Match, obj1Repl,
+                        obj1Data, obj1Result}, // different trigger, replace
+                {obj1Trigger2, obj1Match, obj1Repl,
+                        obj1Data, obj1Data},  // no trigger, no replace
         };
     }
 
-    @Test(enabled = true, dataProvider = "MatchReplaceData")
-    static void test3(byte[] match, byte[] replace,
+    @Test(dataProvider = "MatchReplaceData")
+    public static void test1(byte[] trigger, byte[] match, byte[] replace,
                       byte[] input, byte[] expected) {
-        System.out.printf("match: %s, replace: %s%n", Arrays.toString(match), Arrays.toString(replace));
+        System.out.printf("trigger: %s, match: %s, replace: %s%n", Arrays.toString(trigger),
+                Arrays.toString(match), Arrays.toString(replace));
         try (ByteArrayOutputStream output = new ByteArrayOutputStream();
         ByteArrayOutputStream log = new ByteArrayOutputStream();
              OutputStream out = new MatchReplaceOutputStream(output, "test3",
-                     log, match, replace)) {
+                     log, trigger, match, replace)) {
             out.write(input);
             byte[] actual = output.toByteArray();
 
@@ -564,7 +788,4 @@
             Assert.fail("unexpected exception", ioe);
         }
     }
-
-
-
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/management/remote/mandatory/connection/DefaultAgentFilterTest.java	Tue Jan 16 22:58:44 2018 -0800
@@ -0,0 +1,327 @@
+/*
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+ /*
+ * @test
+ * @bug 8159377
+ * @library /lib/testlibrary
+ * @summary Tests ObjectFilter on default agent
+ * @author Harsha Wardhana B
+ * @build jdk.testlibrary.* DefaultAgentFilterTest
+ * @run main/othervm/timeout=600 -XX:+UsePerfData DefaultAgentFilterTest
+ */
+import java.io.EOFException;
+import java.io.File;
+import java.io.IOException;
+import java.io.InvalidClassException;
+import java.io.Serializable;
+import java.lang.reflect.InvocationTargetException;
+import java.net.BindException;
+import java.rmi.UnmarshalException;
+import java.rmi.registry.LocateRegistry;
+import java.rmi.registry.Registry;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicBoolean;
+import javax.management.MBeanServerConnection;
+import javax.management.ObjectName;
+import javax.management.remote.JMXConnector;
+import javax.management.remote.JMXConnectorFactory;
+import javax.management.remote.JMXServiceURL;
+import java.util.concurrent.TimeUnit;
+
+import jdk.testlibrary.ProcessTools;
+import jdk.testlibrary.Utils;
+
+public class DefaultAgentFilterTest {
+
+    public static class MyTestObject implements Serializable {
+
+        String a;
+        int id;
+    }
+
+    public interface TestMBean {
+
+        public void op1(HashSet<Object> params);
+
+        public void op2(String s, HashSet<String> params);
+
+        public void op3(MyTestObject obj, String s, HashMap<String, String> param);
+    }
+
+    public static class Test implements TestMBean {
+
+        @Override
+        public void op1(HashSet<Object> params) {
+            System.out.println("Invoked op1");
+        }
+
+        @Override
+        public void op2(String s, HashSet<String> params) {
+            System.out.println("Invoked op2");
+        }
+
+        @Override
+        public void op3(MyTestObject obj, String s, HashMap<String, String> param) {
+            System.out.println("Invoked op3");
+        }
+    }
+
+    private static class TestAppRun implements AutoCloseable {
+
+        private Process p;
+        private final ProcessBuilder pb;
+        private final String name;
+        private final AtomicBoolean started = new AtomicBoolean(false);
+
+        public TestAppRun(ProcessBuilder pb, String name) {
+            this.pb = pb;
+            this.name = name;
+        }
+
+        public synchronized void start() throws Exception {
+            if (started.compareAndSet(false, true)) {
+                try {
+                    AtomicBoolean error = new AtomicBoolean(false);
+                    AtomicBoolean bindError = new AtomicBoolean(false);
+                    p = ProcessTools.startProcess(
+                            TEST_APP_NAME + "{" + name + "}",
+                            pb,
+                            (line) -> {
+                                if (line.toLowerCase().contains("exception")
+                                || line.toLowerCase().contains("error")) {
+                                    error.set(true);
+                                }
+                                bindError.set(line.toLowerCase().contains("bindexception"));
+                                return true;
+                            }, 10, TimeUnit.SECONDS);
+                    if (bindError.get()) {
+                        throw new BindException("Process could not be started");
+                    } else if (error.get()) {
+                        throw new RuntimeException();
+                    }
+                } catch (Exception ex) {
+                    if (p != null) {
+                        p.destroy();
+                        p.waitFor();
+                    }
+                    throw ex;
+                }
+            }
+        }
+
+        public synchronized void stop()
+                throws IOException, InterruptedException {
+            if (started.compareAndSet(true, false)) {
+                p.getOutputStream().write(0);
+                p.getOutputStream().flush();
+                int ec = p.waitFor();
+                if (ec != 0) {
+                    StringBuilder msg = new StringBuilder();
+                    msg.append("Test application '").append(name);
+                    msg.append("' failed with exit code: ");
+                    msg.append(ec);
+                    System.err.println(msg);
+                }
+            }
+        }
+
+        @Override
+        public void close() throws Exception {
+            stop();
+        }
+    }
+
+    private static final String TEST_APP_NAME = "TestApp";
+
+    private static void testDefaultAgent(String propertyFile) throws Exception {
+        int port = Utils.getFreePort();
+        String propFile = System.getProperty("test.src") + File.separator + propertyFile;
+        List<String> pbArgs = new ArrayList<>(Arrays.asList(
+                "-cp",
+                System.getProperty("test.class.path"),
+                "-XX:+UsePerfData"
+        ));
+        String[] args = new String[]{
+            "-Dcom.sun.management.jmxremote.port=" + port,
+            "-Dcom.sun.management.jmxremote.authenticate=false",
+            "-Dcom.sun.management.jmxremote.ssl=false",
+            "-Dcom.sun.management.config.file=" + propFile
+        };
+        pbArgs.addAll(Arrays.asList(args));
+        pbArgs.add(TEST_APP_NAME);
+
+        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
+                pbArgs.toArray(new String[pbArgs.size()])
+        );
+
+        try (TestAppRun s = new TestAppRun(pb, DefaultAgentFilterTest.class.getSimpleName())) {
+            s.start();
+            JMXServiceURL url = testConnect(port);
+            testMBeanOperations(url);
+        }
+    }
+
+    private static JMXServiceURL testConnect(int port) throws Exception {
+        EOFException lastException = null;
+        JMXServiceURL url = null;
+        // factor adjusted timeout (5 seconds) for the RMI to become available
+        long timeout = System.currentTimeMillis() + Utils.adjustTimeout(5000);
+        do {
+            lastException = null;
+            try {
+                Registry registry = LocateRegistry.getRegistry(port);
+                String[] relist = registry.list();
+                for (int i = 0; i < relist.length; ++i) {
+                    System.out.println("Got registry: " + relist[i]);
+                }
+                String jmxUrlStr = String.format(
+                        "service:jmx:rmi:///jndi/rmi://localhost:%d/jmxrmi",
+                        port);
+                url = new JMXServiceURL(jmxUrlStr);
+
+                try (JMXConnector c = JMXConnectorFactory.connect(url, null)) {
+                    MBeanServerConnection conn = c.getMBeanServerConnection();
+                    ObjectName name = new ObjectName("jtreg:type=Test");
+                    conn.createMBean(Test.class.getName(), name);
+                }
+            } catch (Exception ex) {
+                if (ex instanceof EOFException) {
+                    lastException = (EOFException) ex;
+                    System.out.println("Error establishing RMI connection. Retrying in 500ms.");
+                    Thread.sleep(500);
+                } else {
+                    throw ex;
+                }
+            }
+        } while (lastException != null && System.currentTimeMillis() < timeout);
+        if (lastException != null) {
+            throw lastException;
+        }
+        return url;
+    }
+
+    public static void main(String[] args) throws Exception {
+        System.out.println("---" + DefaultAgentFilterTest.class.getName() + "-main: starting ...");
+
+        boolean retry = false;
+        do {
+            try {
+                // blacklist String
+                testDefaultAgent("mgmt1.properties");
+                System.out.println("----\tTest FAILED !!");
+                throw new RuntimeException("---" + DefaultAgentFilterTest.class.getName() + " - No exception reported");
+            } catch (Exception ex) {
+                if (ex instanceof InvocationTargetException) {
+                    if (ex.getCause() instanceof BindException
+                            || ex.getCause() instanceof java.rmi.ConnectException) {
+                        System.out.println("Failed to allocate ports. Retrying ...");
+                        retry = true;
+                    }
+                } else if (ex instanceof InvalidClassException) {
+                    System.out.println("----\tTest PASSED !!");
+                } else if (ex instanceof UnmarshalException
+                        && ((UnmarshalException) ex).getCause() instanceof InvalidClassException) {
+                    System.out.println("----\tTest PASSED !!");
+                } else {
+                    System.out.println(ex);
+                    System.out.println("----\tTest FAILED !!");
+                    throw ex;
+                }
+            }
+        } while (retry);
+        retry = false;
+        do {
+            try {
+                // blacklist non-existent class
+                testDefaultAgent("mgmt2.properties");
+                System.out.println("----\tTest PASSED !!");
+            } catch (Exception ex) {
+                if (ex instanceof InvocationTargetException) {
+                    if (ex.getCause() instanceof BindException
+                            || ex.getCause() instanceof java.rmi.ConnectException) {
+                        System.out.println("Failed to allocate ports. Retrying ...");
+                        retry = true;
+                    }
+                } else {
+                    System.out.println(ex);
+                    System.out.println("----\tTest FAILED !!");
+                    throw ex;
+                }
+            }
+        } while (retry);
+
+        System.out.println("---" + DefaultAgentFilterTest.class.getName() + "-main: finished ...");
+    }
+
+    private static void testMBeanOperations(JMXServiceURL serverUrl) throws Exception {
+        Map<String, Object> clientEnv = new HashMap<>(1);
+        ObjectName name = new ObjectName("jtreg:type=Test");
+        try (JMXConnector client = JMXConnectorFactory.connect(serverUrl, clientEnv)) {
+            MBeanServerConnection conn = client.getMBeanServerConnection();
+
+            HashSet<String> set = new HashSet<>();
+            set.add("test1");
+            set.add("test2");
+
+            String a = "A";
+
+            Object[] params1 = {set};
+            String[] sig1 = {HashSet.class.getName()};
+            conn.invoke(name, "op1", params1, sig1);
+
+            Object[] params2 = {a, set};
+            String[] sig2 = {String.class.getName(), HashSet.class.getName()};
+            conn.invoke(name, "op2", params2, sig2);
+
+            HashMap<String, String> map = new HashMap<>();
+            map.put("a", "A");
+            map.put("b", "B");
+
+            Object[] params3 = {new MyTestObject(), a, map};
+            String[] sig3 = {MyTestObject.class.getName(), String.class.getName(),
+                HashMap.class.getName()};
+            conn.invoke(name, "op3", params3, sig3);
+        }
+    }
+}
+
+class TestApp {
+
+    private static void doSomething() throws IOException {
+        int r = System.in.read();
+        System.out.println("read: " + r);
+    }
+
+    public static void main(String args[]) throws Exception {
+        System.out.println("main enter");
+        System.out.flush();
+        doSomething();
+        System.out.println("main exit");
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/management/remote/mandatory/connection/NewRMIClientFilterTest.java	Tue Jan 16 22:58:44 2018 -0800
@@ -0,0 +1,146 @@
+/*
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+ /*
+ * @test
+ * @bug 8159377
+ * @summary Tests ObjectInputFilter on RMIServer.newClient
+ * @author Harsha Wardhana B
+ * @run clean NewRMIClientFilterTest
+ * @run build NewRMIClientFilterTest
+ * @run main NewRMIClientFilterTest
+ */
+import java.io.InvalidClassException;
+import java.io.Serializable;
+import java.lang.management.ManagementFactory;
+import java.util.HashMap;
+import java.util.Map;
+import javax.management.remote.JMXConnector;
+import javax.management.remote.JMXConnectorFactory;
+import javax.management.remote.JMXConnectorServer;
+import javax.management.remote.JMXConnectorServerFactory;
+import javax.management.remote.JMXServiceURL;
+import com.sun.jmx.remote.util.EnvHelp;
+
+public class NewRMIClientFilterTest {
+
+    public static void main(String[] args) throws Exception {
+        System.out.println("---NewRMIClientFilterTest-main: starting ...");
+        String filter1 = java.lang.String.class.getName() + ";!*";
+        String filter2 = java.lang.String.class.getName() + ";" + MyCredentials.class.getName() + ";!*";
+
+        JMXServiceURL url = new JMXServiceURL("rmi", null, 0);
+        JMXServiceURL serverUrl = null;
+        Map<String, Object> env = new HashMap<>(1);
+        JMXConnectorServer server = null;
+
+        System.out.println("\n---NewRMIClientFilterTest-main: testing types = null");
+        server = newServer(url, null);
+        serverUrl = server.getAddress();
+        doTest(serverUrl, null);
+        doTest(serverUrl, new String[]{"toto", "titi"});
+        doTest(serverUrl, new Object[]{new MyCredentials(), "toto"});
+        server.stop();
+
+        System.out.println("\n---NewRMIClientFilterTest-main: testing types = String[]");
+        env.put(EnvHelp.CREDENTIALS_FILTER_PATTERN,
+                filter1);
+        server = newServer(url, env);
+        serverUrl = server.getAddress();
+        doTest(serverUrl, null);
+        doTest(serverUrl, new String[]{"toto", "titi"});
+        try {
+            doTest(serverUrl, new MyCredentials());
+            throw new Error("Bad client is not refused!");
+        } catch (Exception e) {
+            isInvalidClassEx(e);
+        } finally {
+            server.stop();
+        }
+
+        System.out.println("\n---NewRMIClientFilterTest-main: testing user specific types = String, MyCredentials");
+        env.put(EnvHelp.CREDENTIALS_FILTER_PATTERN,
+                filter2);
+        server = newServer(url, env);
+        serverUrl = server.getAddress();
+        doTest(serverUrl, null);
+        doTest(serverUrl, new String[]{"toto", "titi"});
+        doTest(serverUrl, new MyCredentials[]{new MyCredentials(), (MyCredentials) null});
+        try {
+            doTest(serverUrl, new Object[]{"toto", new byte[3]});
+            throw new Error("Bad client is not refused!");
+        } catch (Exception e) {
+            isInvalidClassEx(e);
+        } finally {
+            server.stop();
+        }
+
+        System.out.println("---NewRMIClientFilterTest-main PASSED!!!");
+    }
+
+    private static void doTest(JMXServiceURL serverAddr, Object credentials) throws Exception {
+        System.out.println("---NewRMIClientFilterTest-test:\n\tserver address: "
+                + serverAddr + "\n\tcredentials: " + credentials);
+
+        Map<String, Object> env = new HashMap<>(1);
+        env.put("jmx.remote.credentials", credentials);
+        JMXConnector client = null;
+        try {
+            client = JMXConnectorFactory.connect(serverAddr, env);
+            client.getMBeanServerConnection().getDefaultDomain();
+        } finally {
+            try {
+                client.close();
+            } catch (Exception e) {
+            }
+        }
+        System.out.println("---NewRMIClientFilterTest-test: PASSED!");
+    }
+
+    private static JMXConnectorServer newServer(JMXServiceURL url, Map<String, Object> env)
+            throws Exception {
+        JMXConnectorServer server = JMXConnectorServerFactory.newJMXConnectorServer(
+                url,
+                env,
+                ManagementFactory.getPlatformMBeanServer());
+
+        server.start();
+        return server;
+    }
+
+    private static class MyCredentials implements Serializable {
+    }
+
+    private static void isInvalidClassEx(Exception e) {
+        Throwable cause = e;
+        while (cause != null) {
+            if (cause instanceof InvalidClassException) {
+                System.out.println("---NewRMIClientFilterTest-InvalidClassException expected: " + cause);
+                return;
+            }
+            cause = cause.getCause();
+        }
+        e.printStackTrace();
+        throw new RuntimeException("Did not get expected InvalidClassException!");
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/management/remote/mandatory/connection/mgmt1.properties	Tue Jan 16 22:58:44 2018 -0800
@@ -0,0 +1,34 @@
+# ################ Filter for ObjectInputStream #############################
+com.sun.management.jmxremote.serial.filter.pattern=!DefaultAgentFilterTest$MyTestObject
+#   A filter, if configured, is used by java.io.ObjectInputStream during
+#   deserialization of parameters sent to the JMX default agent to validate the 
+#   contents of the stream.
+#   A filter is configured as a sequence of patterns, each pattern is either
+#   matched against the name of a class in the stream or defines a limit.
+#   Patterns are separated by ";" (semicolon).
+#   Whitespace is significant and is considered part of the pattern.
+#
+#   If a pattern includes a "=", it sets a limit.
+#   If a limit appears more than once the last value is used.
+#   Limits are checked before classes regardless of the order in the sequence of patterns.
+#   If any of the limits are exceeded, the filter status is REJECTED.
+#
+#       maxdepth=value - the maximum depth of a graph
+#       maxrefs=value  - the maximum number of internal references
+#       maxbytes=value - the maximum number of bytes in the input stream
+#       maxarray=value - the maximum array length allowed
+#
+#   Other patterns, from left to right, match the class or package name as
+#   returned from Class.getName.
+#   If the class is an array type, the class or package to be matched is the element type.
+#   Arrays of any number of dimensions are treated the same as the element type.
+#   For example, a pattern of "!example.Foo", rejects creation of any instance or
+#   array of example.Foo.
+#
+#   If the pattern starts with "!", the status is REJECTED if the remaining pattern
+#       is matched; otherwise the status is ALLOWED if the pattern matches.
+#   If the pattern ends with ".**" it matches any class in the package and all subpackages.
+#   If the pattern ends with ".*" it matches any class in the package.
+#   If the pattern ends with "*", it matches any class with the pattern as a prefix.
+#   If the pattern is equal to the class name, it matches.
+#   Otherwise, the status is UNDECIDED.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/management/remote/mandatory/connection/mgmt2.properties	Tue Jan 16 22:58:44 2018 -0800
@@ -0,0 +1,34 @@
+# ################ Filter for ObjectInputStream #############################
+com.sun.management.jmxremote.serial.filter.pattern=!DefaultAgentFilterTest$ThisTypeIsNotUsed
+#   A filter, if configured, is used by java.io.ObjectInputStream during
+#   deserialization of parameters sent to the JMX default agent to validate the 
+#   contents of the stream.
+#   A filter is configured as a sequence of patterns, each pattern is either
+#   matched against the name of a class in the stream or defines a limit.
+#   Patterns are separated by ";" (semicolon).
+#   Whitespace is significant and is considered part of the pattern.
+#
+#   If a pattern includes a "=", it sets a limit.
+#   If a limit appears more than once the last value is used.
+#   Limits are checked before classes regardless of the order in the sequence of patterns.
+#   If any of the limits are exceeded, the filter status is REJECTED.
+#
+#       maxdepth=value - the maximum depth of a graph
+#       maxrefs=value  - the maximum number of internal references
+#       maxbytes=value - the maximum number of bytes in the input stream
+#       maxarray=value - the maximum array length allowed
+#
+#   Other patterns, from left to right, match the class or package name as
+#   returned from Class.getName.
+#   If the class is an array type, the class or package to be matched is the element type.
+#   Arrays of any number of dimensions are treated the same as the element type.
+#   For example, a pattern of "!example.Foo", rejects creation of any instance or
+#   array of example.Foo.
+#
+#   If the pattern starts with "!", the status is REJECTED if the remaining pattern
+#       is matched; otherwise the status is ALLOWED if the pattern matches.
+#   If the pattern ends with ".**" it matches any class in the package and all subpackages.
+#   If the pattern ends with ".*" it matches any class in the package.
+#   If the pattern ends with "*", it matches any class with the pattern as a prefix.
+#   If the pattern is equal to the class name, it matches.
+#   Otherwise, the status is UNDECIDED.
--- a/test/javax/management/remote/mandatory/connectorServer/RMIExporterTest.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/test/javax/management/remote/mandatory/connectorServer/RMIExporterTest.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2017, 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
@@ -46,6 +46,7 @@
 import javax.management.remote.JMXConnectorServerFactory;
 import javax.management.remote.JMXServiceURL;
 import com.sun.jmx.remote.internal.RMIExporter;
+import sun.misc.ObjectInputFilter;
 
 public class RMIExporterTest {
 
@@ -59,7 +60,8 @@
         public Remote exportObject(Remote obj,
                                    int port,
                                    RMIClientSocketFactory csf,
-                                   RMIServerSocketFactory ssf)
+                                   RMIServerSocketFactory ssf,
+                                   ObjectInputFilter unused)
             throws RemoteException {
             System.out.println("CustomRMIExporter::exportObject():: " +
                                "Remote = " + obj);
--- a/test/javax/management/remote/nonLocalAccess/NonLocalJMXRemoteTest.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/test/javax/management/remote/nonLocalAccess/NonLocalJMXRemoteTest.java	Tue Jan 16 22:58:44 2018 -0800
@@ -44,14 +44,37 @@
  * This tests the SingleEntryRegistry implemented by JMX.
  * This test is a manual test and uses JMX running on a *different* host.
  * JMX can be enabled in any Java runtime; for example:
- * login or ssh to the different host and invoke rmiregistry with arguments below.
+ *
+ * Note: Use remote host with latest JDK update release for invoking rmiregistry.
+ *
+ * Note: Test should be ran twice once using arg1 and once using arg2.
+ *
+ * login or ssh to the remote host and invoke rmiregistry with arg1.
  * It will not show any output.
- * {@code $JDK_HOME/bin/rmiregistry \
+ * Execute the test, after test completes execution, stop the server.
+ *
+ * repeat above step using arg2 and execute the test.
+ *
+ *
+ * arg1: {@code $JDK_HOME/bin/rmiregistry \
  *         -J-Dcom.sun.management.jmxremote.port=8888 \
  *         -J-Dcom.sun.management.jmxremote.local.only=false \
  *         -J-Dcom.sun.management.jmxremote.ssl=false \
  *         -J-Dcom.sun.management.jmxremote.authenticate=false
  * }
+ *
+ *
+ * replace "jmx-registry-host" with the hostname or IP address of the remote host
+ * for property "-J-Dcom.sun.management.jmxremote.host" below.
+ *
+ * arg2: {@code $JDK_HOME/bin/rmiregistry \
+ *         -J-Dcom.sun.management.jmxremote.port=8888 \
+ *         -J-Dcom.sun.management.jmxremote.local.only=false \
+ *         -J-Dcom.sun.management.jmxremote.ssl=false \
+ *         -J-Dcom.sun.management.jmxremote.authenticate=false \
+ *         -J-Dcom.sun.management.jmxremote.host="jmx-registry-host"
+ * }
+ *
  * On the first host modify the @run command above to replace "jmx-registry-host"
  * with the hostname or IP address of the different host and run the test with jtreg.
  */
@@ -132,6 +155,7 @@
             if (asIndex < 0 ||
                     disallowIndex < 0 ||
                     nonLocalHostIndex < 0 ) {
+                System.out.println("Exception message is " + msg);
                 throw new RuntimeException("exception message is malformed", t);
             }
             System.out.printf("Found expected AccessException: %s%n%n", t);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/net/ssl/templates/SSLSocketTemplate.java	Tue Jan 16 22:58:44 2018 -0800
@@ -0,0 +1,844 @@
+/*
+ * Copyright (c) 2016, 2017, 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.
+ */
+
+//
+// Please run in othervm mode.  SunJSSE does not support dynamic system
+// properties, no way to re-use system properties in samevm/agentvm mode.
+//
+
+/*
+ * @test
+ * @bug 8161106 8170329
+ * @modules jdk.crypto.ec
+ * @summary Improve SSLSocket test template
+ * @run main/othervm SSLSocketTemplate
+ */
+
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLServerSocket;
+import javax.net.ssl.SSLServerSocketFactory;
+import javax.net.ssl.SSLSocket;
+import javax.net.ssl.SSLSocketFactory;
+import javax.net.ssl.TrustManagerFactory;
+import java.net.InetSocketAddress;
+import java.net.SocketTimeoutException;
+import java.security.KeyStore;
+import java.security.PrivateKey;
+import java.security.KeyFactory;
+import java.security.cert.Certificate;
+import java.security.cert.CertificateFactory;
+import java.security.spec.PKCS8EncodedKeySpec;
+import java.util.Base64;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Template to help speed your client/server tests.
+ *
+ * Two examples that use this template:
+ *    test/sun/security/ssl/ServerHandshaker/AnonCipherWithWantClientAuth.java
+ *    test/sun/net/www/protocol/https/HttpsClient/ServerIdentityTest.java
+ */
+public class SSLSocketTemplate {
+
+    /*
+     * ==================
+     * Run the test case.
+     */
+    public static void main(String[] args) throws Exception {
+        (new SSLSocketTemplate()).run();
+    }
+
+    /*
+     * Run the test case.
+     */
+    public void run() throws Exception {
+        bootup();
+    }
+
+    /*
+     * Define the server side application of the test for the specified socket.
+     */
+    protected void runServerApplication(SSLSocket socket) throws Exception {
+        // here comes the test logic
+        InputStream sslIS = socket.getInputStream();
+        OutputStream sslOS = socket.getOutputStream();
+
+        sslIS.read();
+        sslOS.write(85);
+        sslOS.flush();
+    }
+
+    /*
+     * Define the client side application of the test for the specified socket.
+     * This method is used if the returned value of
+     * isCustomizedClientConnection() is false.
+     *
+     * @param socket may be null is no client socket is generated.
+     *
+     * @see #isCustomizedClientConnection()
+     */
+    protected void runClientApplication(SSLSocket socket) throws Exception {
+        InputStream sslIS = socket.getInputStream();
+        OutputStream sslOS = socket.getOutputStream();
+
+        sslOS.write(280);
+        sslOS.flush();
+        sslIS.read();
+    }
+
+    /*
+     * Define the client side application of the test for the specified
+     * server port.  This method is used if the returned value of
+     * isCustomizedClientConnection() is true.
+     *
+     * Note that the client need to connect to the server port by itself
+     * for the actual message exchange.
+     *
+     * @see #isCustomizedClientConnection()
+     */
+    protected void runClientApplication(int serverPort) throws Exception {
+        // blank
+    }
+
+    /*
+     * Create an instance of SSLContext for client use.
+     */
+    protected SSLContext createClientSSLContext() throws Exception {
+        return createSSLContext(trustedCertStrs,
+                endEntityCertStrs, endEntityPrivateKeys,
+                endEntityPrivateKeyNames,
+                getClientContextParameters());
+    }
+
+    /*
+     * Create an instance of SSLContext for server use.
+     */
+    protected SSLContext createServerSSLContext() throws Exception {
+        return createSSLContext(trustedCertStrs,
+                endEntityCertStrs, endEntityPrivateKeys,
+                endEntityPrivateKeyNames,
+                getServerContextParameters());
+    }
+
+    /*
+     * The parameters used to configure SSLContext.
+     */
+    protected static final class ContextParameters {
+        final String contextProtocol;
+        final String tmAlgorithm;
+        final String kmAlgorithm;
+
+        ContextParameters(String contextProtocol,
+                String tmAlgorithm, String kmAlgorithm) {
+
+            this.contextProtocol = contextProtocol;
+            this.tmAlgorithm = tmAlgorithm;
+            this.kmAlgorithm = kmAlgorithm;
+        }
+    }
+
+    /*
+     * Get the client side parameters of SSLContext.
+     */
+    protected ContextParameters getClientContextParameters() {
+        return new ContextParameters("TLS", "PKIX", "NewSunX509");
+    }
+
+    /*
+     * Get the server side parameters of SSLContext.
+     */
+    protected ContextParameters getServerContextParameters() {
+        return new ContextParameters("TLS", "PKIX", "NewSunX509");
+    }
+
+    /*
+     * Does the client side use customized connection other than
+     * explicit Socket.connect(), for example, URL.openConnection()?
+     */
+    protected boolean isCustomizedClientConnection() {
+        return false;
+    }
+
+    /*
+     * Configure the server side socket.
+     */
+    protected void configureServerSocket(SSLServerSocket socket) {
+
+    }
+
+    /*
+     * =============================================
+     * Define the client and server side operations.
+     *
+     * If the client or server is doing some kind of object creation
+     * that the other side depends on, and that thread prematurely
+     * exits, you may experience a hang.  The test harness will
+     * terminate all hung threads after its timeout has expired,
+     * currently 3 minutes by default, but you might try to be
+     * smart about it....
+     */
+
+    /*
+     * Is the server ready to serve?
+     */
+    private final CountDownLatch serverCondition = new CountDownLatch(1);
+
+    /*
+     * Is the client ready to handshake?
+     */
+    private final CountDownLatch clientCondition = new CountDownLatch(1);
+
+    /*
+     * What's the server port?  Use any free port by default
+     */
+    private volatile int serverPort = 0;
+
+    /*
+     * Define the server side of the test.
+     */
+    private void doServerSide() throws Exception {
+        // kick start the server side service
+        SSLContext context = createServerSSLContext();
+        SSLServerSocketFactory sslssf = context.getServerSocketFactory();
+        SSLServerSocket sslServerSocket =
+                (SSLServerSocket)sslssf.createServerSocket(serverPort);
+        configureServerSocket(sslServerSocket);
+        serverPort = sslServerSocket.getLocalPort();
+
+        // Signal the client, the server is ready to accept connection.
+        serverCondition.countDown();
+
+        // Try to accept a connection in 30 seconds.
+        SSLSocket sslSocket;
+        try {
+            sslServerSocket.setSoTimeout(30000);
+            sslSocket = (SSLSocket)sslServerSocket.accept();
+        } catch (SocketTimeoutException ste) {
+            // Ignore the test case if no connection within 30 seconds.
+            System.out.println(
+                "No incoming client connection in 30 seconds. " +
+                "Ignore in server side.");
+            return;
+        } finally {
+            sslServerSocket.close();
+        }
+
+        // handle the connection
+        try {
+            // Is it the expected client connection?
+            //
+            // Naughty test cases or third party routines may try to
+            // connection to this server port unintentionally.  In
+            // order to mitigate the impact of unexpected client
+            // connections and avoid intermittent failure, it should
+            // be checked that the accepted connection is really linked
+            // to the expected client.
+            boolean clientIsReady =
+                    clientCondition.await(30L, TimeUnit.SECONDS);
+
+            if (clientIsReady) {
+                // Run the application in server side.
+                runServerApplication(sslSocket);
+            } else {    // Otherwise, ignore
+                // We don't actually care about plain socket connections
+                // for TLS communication testing generally.  Just ignore
+                // the test if the accepted connection is not linked to
+                // the expected client or the client connection timeout
+                // in 30 seconds.
+                System.out.println(
+                        "The client is not the expected one or timeout. " +
+                        "Ignore in server side.");
+            }
+        } finally {
+            sslSocket.close();
+        }
+    }
+
+    /*
+     * Define the client side of the test.
+     */
+    private void doClientSide() throws Exception {
+
+        // Wait for server to get started.
+        //
+        // The server side takes care of the issue if the server cannot
+        // get started in 90 seconds.  The client side would just ignore
+        // the test case if the serer is not ready.
+        boolean serverIsReady =
+                serverCondition.await(90L, TimeUnit.SECONDS);
+        if (!serverIsReady) {
+            System.out.println(
+                    "The server is not ready yet in 90 seconds. " +
+                    "Ignore in client side.");
+            return;
+        }
+
+        if (isCustomizedClientConnection()) {
+            // Signal the server, the client is ready to communicate.
+            clientCondition.countDown();
+
+            // Run the application in client side.
+            runClientApplication(serverPort);
+
+            return;
+        }
+
+        SSLContext context = createClientSSLContext();
+        SSLSocketFactory sslsf = context.getSocketFactory();
+
+        try (SSLSocket sslSocket = (SSLSocket)sslsf.createSocket()) {
+            try {
+                sslSocket.connect(
+                        new InetSocketAddress("localhost", serverPort), 15000);
+            } catch (IOException ioe) {
+                // The server side may be impacted by naughty test cases or
+                // third party routines, and cannot accept connections.
+                //
+                // Just ignore the test if the connection cannot be
+                // established.
+                System.out.println(
+                        "Cannot make a connection in 15 seconds. " +
+                        "Ignore in client side.");
+                return;
+            }
+
+            // OK, here the client and server get connected.
+
+            // Signal the server, the client is ready to communicate.
+            clientCondition.countDown();
+
+            // There is still a chance in theory that the server thread may
+            // wait client-ready timeout and then quit.  The chance should
+            // be really rare so we don't consider it until it becomes a
+            // real problem.
+
+            // Run the application in client side.
+            runClientApplication(sslSocket);
+        }
+    }
+
+    /*
+     * =============================================
+     * Stuffs to customize the SSLContext instances.
+     */
+
+    /*
+     * =======================================
+     * Certificates and keys used in the test.
+     */
+    // Trusted certificates.
+    private final static String[] trustedCertStrs = {
+        // SHA256withECDSA, curve prime256v1
+        // Validity
+        //    Not Before: Nov 25 04:19:51 2016 GMT
+        //    Not After : Nov  5 04:19:51 2037 GMT
+        // Subject Key Identifier:
+        //    CA:48:E8:00:C1:42:BD:59:9B:79:D9:B4:B4:CE:3F:68:0C:C8:C4:0C
+        "-----BEGIN CERTIFICATE-----\n" +
+        "MIICHDCCAcGgAwIBAgIJAJtKs6ZEcVjxMAoGCCqGSM49BAMCMDsxCzAJBgNVBAYT\n" +
+        "AlVTMQ0wCwYDVQQKEwRKYXZhMR0wGwYDVQQLExRTdW5KU1NFIFRlc3QgU2VyaXZj\n" +
+        "ZTAeFw0xNjExMjUwNDE5NTFaFw0zNzExMDUwNDE5NTFaMDsxCzAJBgNVBAYTAlVT\n" +
+        "MQ0wCwYDVQQKEwRKYXZhMR0wGwYDVQQLExRTdW5KU1NFIFRlc3QgU2VyaXZjZTBZ\n" +
+        "MBMGByqGSM49AgEGCCqGSM49AwEHA0IABKMO/AFDHZia65RaqMIBX7WBdtzFj8fz\n" +
+        "ggqMADLJhoszS6qfTUDYskETw3uHfB3KAOENsoKX446qFFPuVjxS1aejga0wgaow\n" +
+        "HQYDVR0OBBYEFMpI6ADBQr1Zm3nZtLTOP2gMyMQMMGsGA1UdIwRkMGKAFMpI6ADB\n" +
+        "Qr1Zm3nZtLTOP2gMyMQMoT+kPTA7MQswCQYDVQQGEwJVUzENMAsGA1UEChMESmF2\n" +
+        "YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2WCCQCbSrOmRHFY8TAPBgNV\n" +
+        "HRMBAf8EBTADAQH/MAsGA1UdDwQEAwIBBjAKBggqhkjOPQQDAgNJADBGAiEA5cJ/\n" +
+        "jirBbXxzpZ6kdp/Zb/yrIBnr4jiPGJTLgRTb8s4CIQChUDfP1Zqg0qJVfqFNaL4V\n" +
+        "a0EAeJHXGZnvCGGqHzoxkg==\n" +
+        "-----END CERTIFICATE-----",
+
+        // SHA256withRSA, 2048 bits
+        // Validity
+        //     Not Before: Nov 25 04:20:02 2016 GMT
+        //     Not After : Nov  5 04:20:02 2037 GMT
+        // Subject Key Identifier:
+        //     A2:DC:55:38:E4:47:7C:8B:D3:E0:CA:FA:AD:3A:C8:4A:DD:12:A0:8E
+        "-----BEGIN CERTIFICATE-----\n" +
+        "MIIDpzCCAo+gAwIBAgIJAO586A+hYNXaMA0GCSqGSIb3DQEBCwUAMDsxCzAJBgNV\n" +
+        "BAYTAlVTMQ0wCwYDVQQKEwRKYXZhMR0wGwYDVQQLExRTdW5KU1NFIFRlc3QgU2Vy\n" +
+        "aXZjZTAeFw0xNjExMjUwNDIwMDJaFw0zNzExMDUwNDIwMDJaMDsxCzAJBgNVBAYT\n" +
+        "AlVTMQ0wCwYDVQQKEwRKYXZhMR0wGwYDVQQLExRTdW5KU1NFIFRlc3QgU2VyaXZj\n" +
+        "ZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMm3veDSU4zKXO0aAHos\n" +
+        "cFRXGLBTe+MUJXAtlkNyx7VKaMZNt5wrUuqzyi/r0LFUdRfNCzZf3X8s8HPHQVii\n" +
+        "29tK0y/yeTn4sJTATSmGaAysMJQpKQcfAQ79ItcEGQ721TFQZ3kOBdgp3t/yUYAP\n" +
+        "K2tFze/QbIw72LE52SBnPPPTzyimNw7Ai2MLl4eQlyMkTs7JS07zIiAO5QYbS8s+\n" +
+        "1NW0A3Y+d0B0q8wYEoHGq7QVjOKlSAksfO0tzi4l0Zu6Uf+J5kMAyZ4ZFgEJvGvw\n" +
+        "y/OKJ+soRFH/5cy1SL8B6AWD1y7WXugeeHTHRW1eOjTxqfG1rZqTVd2lfOMER8y1\n" +
+        "bXcCAwEAAaOBrTCBqjAdBgNVHQ4EFgQUotxVOORHfIvT4Mr6rTrISt0SoI4wawYD\n" +
+        "VR0jBGQwYoAUotxVOORHfIvT4Mr6rTrISt0SoI6hP6Q9MDsxCzAJBgNVBAYTAlVT\n" +
+        "MQ0wCwYDVQQKEwRKYXZhMR0wGwYDVQQLExRTdW5KU1NFIFRlc3QgU2VyaXZjZYIJ\n" +
+        "AO586A+hYNXaMA8GA1UdEwEB/wQFMAMBAf8wCwYDVR0PBAQDAgEGMA0GCSqGSIb3\n" +
+        "DQEBCwUAA4IBAQAtNZJSFeFU6Yid0WSCs2qLAVaTyHsUNSUPUFIIhFAKxdP4DFS0\n" +
+        "+aeOFwdqizAU3kReAYULsfwEBgO51lPBSpB+9coUNQwu7cc8Q5Xqw/llRB0PrINS\n" +
+        "pZl7PW6Ur2ExTBocnUT9A/nhm8iO4PFD/Ly11sf5OdZihhX69NJ2h3a3gcrLjIpO\n" +
+        "L/ewTOgSi5xs+AGGQa+huN3YVL7dh+/rCUvMZVSBX5PloxWS5MMJi0Ui6YjwCFGO\n" +
+        "J4G9m7pI+gJs/x1UG0AgplMF2UCFfiY1SAeE2nKAeOOXAXEwEjFy0ToVTmqXx7fg\n" +
+        "m9YjhuePxlBrd2DF/YW0pc8gmLnrtm4rKPLz\n" +
+        "-----END CERTIFICATE-----",
+
+        // SHA256withDSA, 2048 bits
+        // Validity
+        //     Not Before: Nov 25 04:19:56 2016 GMT
+        //     Not After : Nov  5 04:19:56 2037 GMT
+        // Subject Key Identifier:
+        //     19:46:10:43:24:6A:A5:14:BE:E2:92:01:79:F0:4C:5F:E1:AE:81:B5
+        "-----BEGIN CERTIFICATE-----\n" +
+        "MIIFCzCCBLGgAwIBAgIJAOnEn6YZD/sAMAsGCWCGSAFlAwQDAjA7MQswCQYDVQQG\n" +
+        "EwJVUzENMAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2\n" +
+        "Y2UwHhcNMTYxMTI1MDQxOTU2WhcNMzcxMTA1MDQxOTU2WjA7MQswCQYDVQQGEwJV\n" +
+        "UzENMAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2Uw\n" +
+        "ggNGMIICOQYHKoZIzjgEATCCAiwCggEBAJa17ZYdIChv5yeYuPK3zXxgUEGGsdUD\n" +
+        "AzfQUxtMryCtc3aNgWLxsN1/QYvp9v+hh4twnG20VemCEH9Qlx06Pxg74DwSOA83\n" +
+        "SecO2y7cdgmrHpep9drxKbXVZafwBhbTSwhV+IDO7EO6+LaRvZuya/YOqNIE9ENx\n" +
+        "FVk0NrNsDB6pfDEXZsCZALMN2mcl8KGn1q7vdzJQUEV7F6uLGP33znVfmQyWJH3Y\n" +
+        "W09WVCFXHvDzZHGXDO2O2QwIU1B5AsXnOGeLnKgXzErCoNKwUbVFP0W0OVeJo4pc\n" +
+        "ZfL/8TVELGG90AuuH1V3Gsq6PdzCDPw4Uv/v5m7/6kwXqBQxAJA7jhMCIQCORIGV\n" +
+        "mHy5nBLRhIP4vC7vsTxb4CTApPVmZeL5gTIwtQKCAQB2VZLY22k2+IQM6deRGK3L\n" +
+        "l7tPChGrKnGmTbtUThIza70Sp9DmTBiLzMEY+IgG8kYuT5STVxWjs0cxXCKZGMQW\n" +
+        "tioMtiXPA2M3HA0/8E0mDLSmzb0RAd2xxnDyGsuqo1eVmx7PLjN3bn3EjhD/+j3d\n" +
+        "Jx3ZVScMGyq7sVWppUvpudEXi+2etf6GUHjrcX27juo7u4zQ1ezC/HYG1H+jEFqG\n" +
+        "hdQ6b7H+LBHZH9LegOyIZTMrzAY/TwIr77sXrNJWRoxmDErKB+8bRDybYhNJswlZ\n" +
+        "m0N5YYUlPmepgbl6XzwCv0y0d81h3bayqIPLXEUtRAl9GuM0hNAlA1Y+qSn9xLFY\n" +
+        "A4IBBQACggEAZgWC0uflwqQQP1GRU1tolmFZwyVtKre7SjYgCeQBrOa0Xnj/SLaD\n" +
+        "g1HZ1oH0hccaR/45YouJiCretbbsQ77KouldGSGqTHJgRL75Y2z5uvxa60+YxZ0Z\n" +
+        "v8xvZnj4seyOjgJLxSSYSPl5n/F70RaNiCLVz/kGe6OQ8KoAeQjdDTOHXCegO9KX\n" +
+        "tvhM7EaYc8CII9OIR7S7PXJW0hgLKynZcu/Unh02aM0ABh/uLmw1+tvo8e8KTp98\n" +
+        "NKYSVf6kV3/ya58n4h64UbIYL08JoKUM/5SFETcKAZTU0YKZbpWTM79oJMr8oYVk\n" +
+        "P9jKitNsXq0Xkzt5dSO0kfu/kM7zpnaFsqOBrTCBqjAdBgNVHQ4EFgQUGUYQQyRq\n" +
+        "pRS+4pIBefBMX+GugbUwawYDVR0jBGQwYoAUGUYQQyRqpRS+4pIBefBMX+GugbWh\n" +
+        "P6Q9MDsxCzAJBgNVBAYTAlVTMQ0wCwYDVQQKEwRKYXZhMR0wGwYDVQQLExRTdW5K\n" +
+        "U1NFIFRlc3QgU2VyaXZjZYIJAOnEn6YZD/sAMA8GA1UdEwEB/wQFMAMBAf8wCwYD\n" +
+        "VR0PBAQDAgEGMAsGCWCGSAFlAwQDAgNHADBEAiAwBafz5RRR9nc4cCYoYuBlT/D9\n" +
+        "9eayhkjhBY/zYunypwIgNp/JnFR88/T4hh36QfSKBGXId9RBCM6uaOkOKnEGkps=\n" +
+        "-----END CERTIFICATE-----"
+        };
+
+    // End entity certificate.
+    private final static String[] endEntityCertStrs = {
+        // SHA256withECDSA, curve prime256v1
+        // Validity
+        //     Not Before: Nov 25 04:19:51 2016 GMT
+        //     Not After : Aug 12 04:19:51 2036 GMT
+        // Authority Key Identifier:
+        //     CA:48:E8:00:C1:42:BD:59:9B:79:D9:B4:B4:CE:3F:68:0C:C8:C4:0C
+        "-----BEGIN CERTIFICATE-----\n" +
+        "MIIB1zCCAXygAwIBAgIJAPFq2QL/nUNZMAoGCCqGSM49BAMCMDsxCzAJBgNVBAYT\n" +
+        "AlVTMQ0wCwYDVQQKEwRKYXZhMR0wGwYDVQQLExRTdW5KU1NFIFRlc3QgU2VyaXZj\n" +
+        "ZTAeFw0xNjExMjUwNDE5NTFaFw0zNjA4MTIwNDE5NTFaMFUxCzAJBgNVBAYTAlVT\n" +
+        "MQ0wCwYDVQQKDARKYXZhMR0wGwYDVQQLDBRTdW5KU1NFIFRlc3QgU2VyaXZjZTEY\n" +
+        "MBYGA1UEAwwPUmVncmVzc2lvbiBUZXN0MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcD\n" +
+        "QgAE4yvRGVvy9iVATyuHPJVdX6+lh/GLm/sRJ5qLT/3PVFOoNIvlEVNiARo7xhyj\n" +
+        "2p6bnf32gNg5Ye+QCw20VUv9E6NPME0wCwYDVR0PBAQDAgPoMB0GA1UdDgQWBBSO\n" +
+        "hHlHZQp9hyBfSGTSQWeszqMXejAfBgNVHSMEGDAWgBTKSOgAwUK9WZt52bS0zj9o\n" +
+        "DMjEDDAKBggqhkjOPQQDAgNJADBGAiEAu3t6cvFglBAZfkhZlEwB04ZjUFqyfiRj\n" +
+        "4Hr275E4ZoQCIQDUEonJHlmA19J6oobfR5lYsmoqPm1r0DPm/IiNNKGKKA==\n" +
+        "-----END CERTIFICATE-----",
+
+        // SHA256withRSA, 2048 bits
+        // Validity
+        //     Not Before: Nov 25 04:20:02 2016 GMT
+        //     Not After : Aug 12 04:20:02 2036 GMT
+        // Authority Key Identifier:
+        //     A2:DC:55:38:E4:47:7C:8B:D3:E0:CA:FA:AD:3A:C8:4A:DD:12:A0:8E
+        "-----BEGIN CERTIFICATE-----\n" +
+        "MIIDdjCCAl6gAwIBAgIJAJDcIGOlAmBmMA0GCSqGSIb3DQEBCwUAMDsxCzAJBgNV\n" +
+        "BAYTAlVTMQ0wCwYDVQQKEwRKYXZhMR0wGwYDVQQLExRTdW5KU1NFIFRlc3QgU2Vy\n" +
+        "aXZjZTAeFw0xNjExMjUwNDIwMDJaFw0zNjA4MTIwNDIwMDJaMFUxCzAJBgNVBAYT\n" +
+        "AlVTMQ0wCwYDVQQKDARKYXZhMR0wGwYDVQQLDBRTdW5KU1NFIFRlc3QgU2VyaXZj\n" +
+        "ZTEYMBYGA1UEAwwPUmVncmVzc2lvbiBUZXN0MIIBIjANBgkqhkiG9w0BAQEFAAOC\n" +
+        "AQ8AMIIBCgKCAQEAp0dHrifTg2aY0sH03f2JjK2fW4DL6gLDKq0YirsNE07z54LF\n" +
+        "IeeDio49XwPjB7OpbUTC1hf/YKZ7XiRWyPa1rYozZ88emhZt+cpkyKz+nmW4avlA\n" +
+        "WnrV+gx4+bU9T+WuBWdAraBcq27Y1I26yfCEtC8k3+O0sdlHbhasF+BUDmX/n4+n\n" +
+        "ifJdbNm5eSDx8eFYHFTdjhAud3An2X6QD9WWSoJpPdDi4utHhFAlxW6osjJxsAPv\n" +
+        "zo8YsqmpCMjZcEks4ZsqiZKKiWUWUAjCcbMerDPDX29fyeo348uztvJsmNRzfcwl\n" +
+        "FtwxpYdxuZqwHi2QoNaQTGXjjbZFmjn7qEkjXwIDAQABo2MwYTALBgNVHQ8EBAMC\n" +
+        "A+gwHQYDVR0OBBYEFP+henfufE6Znr60lRkmayadVdxnMB8GA1UdIwQYMBaAFKLc\n" +
+        "VTjkR3yL0+DK+q06yErdEqCOMBIGA1UdEQEB/wQIMAaHBH8AAAEwDQYJKoZIhvcN\n" +
+        "AQELBQADggEBAK56pV2XoAIkrHFTCkWtYX518nuvkzN6a6BqPKALQlmlbJnq/lhV\n" +
+        "tPQx79b0j7tow28l2ze/3M0hRb5Ft/d/7mITZNMR+0owk4U51AU2NacRt7fpoxu5\n" +
+        "wX3hTa4VgX2+BAXeoWF+Yzy6Jj5gAVmSLzBnkTUH0d+EyL1pp+DFE3QdvZqf3+nP\n" +
+        "zkxz15h3iW8FwI+7/19MX2j2XB/sG8mJpqoszWw8lM4qCa2eWyCbqSHhPi+/+rGg\n" +
+        "dDG5uzZeOC845GEH2T3tHDA+F3WwcZG/W+4RR6ZaaHlqPKKMcwFL73YbsqdCiKBv\n" +
+        "p6sXrhIiP0oXImRBRLDlidj5TIOLfAtNM9A=\n" +
+        "-----END CERTIFICATE-----",
+
+        // SHA256withDSA, 2048 bits
+        // Validity
+        //    Not Before: Nov 25 04:19:56 2016 GMT
+        //    Not After : Aug 12 04:19:56 2036 GMT
+        // Authority Key Identifier:
+        //     19:46:10:43:24:6A:A5:14:BE:E2:92:01:79:F0:4C:5F:E1:AE:81:B5
+        "-----BEGIN CERTIFICATE-----\n" +
+        "MIIE2jCCBICgAwIBAgIJAONcI1oba9V9MAsGCWCGSAFlAwQDAjA7MQswCQYDVQQG\n" +
+        "EwJVUzENMAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2\n" +
+        "Y2UwHhcNMTYxMTI1MDQxOTU2WhcNMzYwODEyMDQxOTU2WjBVMQswCQYDVQQGEwJV\n" +
+        "UzENMAsGA1UECgwESmF2YTEdMBsGA1UECwwUU3VuSlNTRSBUZXN0IFNlcml2Y2Ux\n" +
+        "GDAWBgNVBAMMD1JlZ3Jlc3Npb24gVGVzdDCCA0YwggI5BgcqhkjOOAQBMIICLAKC\n" +
+        "AQEAlrXtlh0gKG/nJ5i48rfNfGBQQYax1QMDN9BTG0yvIK1zdo2BYvGw3X9Bi+n2\n" +
+        "/6GHi3CcbbRV6YIQf1CXHTo/GDvgPBI4DzdJ5w7bLtx2Casel6n12vEptdVlp/AG\n" +
+        "FtNLCFX4gM7sQ7r4tpG9m7Jr9g6o0gT0Q3EVWTQ2s2wMHql8MRdmwJkAsw3aZyXw\n" +
+        "oafWru93MlBQRXsXq4sY/ffOdV+ZDJYkfdhbT1ZUIVce8PNkcZcM7Y7ZDAhTUHkC\n" +
+        "xec4Z4ucqBfMSsKg0rBRtUU/RbQ5V4mjilxl8v/xNUQsYb3QC64fVXcayro93MIM\n" +
+        "/DhS/+/mbv/qTBeoFDEAkDuOEwIhAI5EgZWYfLmcEtGEg/i8Lu+xPFvgJMCk9WZl\n" +
+        "4vmBMjC1AoIBAHZVktjbaTb4hAzp15EYrcuXu08KEasqcaZNu1ROEjNrvRKn0OZM\n" +
+        "GIvMwRj4iAbyRi5PlJNXFaOzRzFcIpkYxBa2Kgy2Jc8DYzccDT/wTSYMtKbNvREB\n" +
+        "3bHGcPIay6qjV5WbHs8uM3dufcSOEP/6Pd0nHdlVJwwbKruxVamlS+m50ReL7Z61\n" +
+        "/oZQeOtxfbuO6ju7jNDV7ML8dgbUf6MQWoaF1Dpvsf4sEdkf0t6A7IhlMyvMBj9P\n" +
+        "Aivvuxes0lZGjGYMSsoH7xtEPJtiE0mzCVmbQ3lhhSU+Z6mBuXpfPAK/TLR3zWHd\n" +
+        "trKog8tcRS1ECX0a4zSE0CUDVj6pKf3EsVgDggEFAAKCAQBEGmdP55PyE3M+Q3fU\n" +
+        "dCGq0sbKw/04xPVhaNYRnRKNR82n+wb8bMCI1vvFqXy1BB6svti4mTHbQZ8+bQXm\n" +
+        "gyce67uYMwIa5BIk6omNGCeW/kd4ruPgyFxeb6O/Y/7w6AWyRmQttlxRA5M5OhSC\n" +
+        "tVS4oVC1KK1EfHAUh7mu8S8GrWJoJAWA3PM97Oy/HSGCEUl6HGEu1m7FHPhOKeYG\n" +
+        "cLkSaov5cbCYO76smHchI+tdUciVqeL3YKQdS+KAzsQoeAZIu/WpbaI1V+5/rSG1\n" +
+        "I94uBITLCjlJfJZ1aredCDrRXOFH7qgSBhM8/WzwFpFCnnpbSKMgrcrKubsFmW9E\n" +
+        "jQhXo2MwYTALBgNVHQ8EBAMCA+gwHQYDVR0OBBYEFNA9PhQOjB+05fxxXPNqe0OT\n" +
+        "doCjMB8GA1UdIwQYMBaAFBlGEEMkaqUUvuKSAXnwTF/hroG1MBIGA1UdEQEB/wQI\n" +
+        "MAaHBH8AAAEwCwYJYIZIAWUDBAMCA0cAMEQCIE0LM2sZi+L8tjH9sgjLEwJmYZvO\n" +
+        "yqNfQnXrkTCb+MLMAiBZLaRTVJrOW3edQjum+SonKKuiN22bRclO6pGuNRCtng==\n" +
+        "-----END CERTIFICATE-----"
+        };
+
+    // Private key in the format of PKCS#8.
+    private final static String[] endEntityPrivateKeys = {
+        //
+        // EC private key related to cert endEntityCertStrs[0].
+        //
+        "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgGAy4Pxrd2keM7AdP\n" +
+        "VNUMEO5iO681v4/tstVGfdXkCTuhRANCAATjK9EZW/L2JUBPK4c8lV1fr6WH8Yub\n" +
+        "+xEnmotP/c9UU6g0i+URU2IBGjvGHKPanpud/faA2Dlh75ALDbRVS/0T",
+
+        //
+        // RSA private key related to cert endEntityCertStrs[1].
+        //
+        "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCnR0euJ9ODZpjS\n" +
+        "wfTd/YmMrZ9bgMvqAsMqrRiKuw0TTvPngsUh54OKjj1fA+MHs6ltRMLWF/9gpnte\n" +
+        "JFbI9rWtijNnzx6aFm35ymTIrP6eZbhq+UBaetX6DHj5tT1P5a4FZ0CtoFyrbtjU\n" +
+        "jbrJ8IS0LyTf47Sx2UduFqwX4FQOZf+fj6eJ8l1s2bl5IPHx4VgcVN2OEC53cCfZ\n" +
+        "fpAP1ZZKgmk90OLi60eEUCXFbqiyMnGwA+/OjxiyqakIyNlwSSzhmyqJkoqJZRZQ\n" +
+        "CMJxsx6sM8Nfb1/J6jfjy7O28myY1HN9zCUW3DGlh3G5mrAeLZCg1pBMZeONtkWa\n" +
+        "OfuoSSNfAgMBAAECggEAWnAHKPkPObN2XDvQj1RL0WrtBSOVG2dy7Ne4tQh8ATxm\n" +
+        "UXw56CKq03YjaANJ8xgHObQ7QlSnFTHs8PDkmrIHd1OIh09LVDNcMfhilLwyzKBi\n" +
+        "HDO1vzU6Cn5DyX1bMJ8UfodcSIKyl1zOjdwyaItIs8HpRcJuJtk57SME18PIrh9H\n" +
+        "EWchWSxTvPvKDY2bhb4vBMgVPfTQO3yc8gY/1J5vKPqDpyEuCGjV13zd/AoL/u5A\n" +
+        "sG10hQ2veJ9KAn1xwPwEoAkCdNLL8vPB1rCbeMZNamqHZRihfoOgDnnJIf3FtUFF\n" +
+        "8bS2FM2kGQR+05SZdhBmJl0obPrbBWil/2vxqeFrgQKBgQDZl1yQsFss2BKK2VAh\n" +
+        "9PKc8tU1v6RpHQZhJEDSct2slHQS5DF6bWl5kJiPevXSvcnjgoPamZf7Joii+Rds\n" +
+        "3xtPQmRw2vQmXBQzQS1YoRuh4hUlkdFWCjUNNg1kvipue6FO4PVg3ViP7llN8PXK\n" +
+        "rSpVxn0a36UiN9jN2zMOUs6tJwKBgQDEzlqa7DghMli7TUdL44uvD2/ceiHqHMMw\n" +
+        "5eLsEHeRVn/EVU99beKw/dAOGwRssTpCd9h7fwzQ2503/Qb/Goe0nKE7+xvt3/sE\n" +
+        "n2Y8Qfv1W1+hGb2qU2jhQaR5bZrLZp0+BgRuQ4ttpYvzopYe4FLZWhDBA0zsGyu0\n" +
+        "nCi7lUSrCQKBgGeGYW8hyS9r2l6fiEWvsiLEUnbRKFsuiRN82S6HojpzI0q9sWDL\n" +
+        "X6yMBFn3qa/LxpttRGikPTAsJERN+Tw+ZlLuhrU/J3x8wMumDfomJOx/kYofd5bV\n" +
+        "ImqXtgWhiLSqM5RA6d5dUb6hK3Iu2/LDMuo+ltVLZNkD8y32RbNh6J1vAoGAbLqQ\n" +
+        "pgyhSf3Vtc0Q+aVB87p0k3tKJ1wynl4zSzYhyMLgHakAHIzL8/qVqmVUwXP8euJZ\n" +
+        "UIk1nGHobxk0d1XB6Y+rKEcn+/iFZt1ljx7pQ3ly0L824NXqGKC6bHeYUI1li/Gp\n" +
+        "Gv3oFvCh7D1D8NUAEKLIpMndAohUUhkAC/qAkHkCgYEAzSIarDNquayV+umC1SXm\n" +
+        "Zo6XLuzWjudLxPd2lyCfwR2aRKlrb+5OFYErX+RSLyCJmaqVZMyXP09PBIvNXu2Z\n" +
+        "+gbx5WUC+kA+6zdKEPXowei6i6EHMXYT2AL7395ZbPajZjsCduE3WuUztuHrhtMm\n" +
+        "JI+k1o4rCnSLlX4gWdN1oTs=",
+
+        //
+        // DSA private key related to cert endEntityCertStrs[2].
+        //
+        "MIICZAIBADCCAjkGByqGSM44BAEwggIsAoIBAQCWte2WHSAob+cnmLjyt818YFBB\n" +
+        "hrHVAwM30FMbTK8grXN2jYFi8bDdf0GL6fb/oYeLcJxttFXpghB/UJcdOj8YO+A8\n" +
+        "EjgPN0nnDtsu3HYJqx6XqfXa8Sm11WWn8AYW00sIVfiAzuxDuvi2kb2bsmv2DqjS\n" +
+        "BPRDcRVZNDazbAweqXwxF2bAmQCzDdpnJfChp9au73cyUFBFexerixj99851X5kM\n" +
+        "liR92FtPVlQhVx7w82RxlwztjtkMCFNQeQLF5zhni5yoF8xKwqDSsFG1RT9FtDlX\n" +
+        "iaOKXGXy//E1RCxhvdALrh9VdxrKuj3cwgz8OFL/7+Zu/+pMF6gUMQCQO44TAiEA\n" +
+        "jkSBlZh8uZwS0YSD+Lwu77E8W+AkwKT1ZmXi+YEyMLUCggEAdlWS2NtpNviEDOnX\n" +
+        "kRity5e7TwoRqypxpk27VE4SM2u9EqfQ5kwYi8zBGPiIBvJGLk+Uk1cVo7NHMVwi\n" +
+        "mRjEFrYqDLYlzwNjNxwNP/BNJgy0ps29EQHdscZw8hrLqqNXlZsezy4zd259xI4Q\n" +
+        "//o93Scd2VUnDBsqu7FVqaVL6bnRF4vtnrX+hlB463F9u47qO7uM0NXswvx2BtR/\n" +
+        "oxBahoXUOm+x/iwR2R/S3oDsiGUzK8wGP08CK++7F6zSVkaMZgxKygfvG0Q8m2IT\n" +
+        "SbMJWZtDeWGFJT5nqYG5el88Ar9MtHfNYd22sqiDy1xFLUQJfRrjNITQJQNWPqkp\n" +
+        "/cSxWAQiAiAKHYbYwEy0XS9J0MeKQmqPswn0nCJKvH+esfMKkZvV3w=="
+        };
+
+    // Private key names of endEntityPrivateKeys.
+    private final static String[] endEntityPrivateKeyNames = {
+        "EC",
+        "RSA",
+        "DSA",
+        };
+
+    /*
+     * Create an instance of SSLContext with the specified trust/key materials.
+     */
+    private SSLContext createSSLContext(
+            String[] trustedMaterials,
+            String[] keyMaterialCerts,
+            String[] keyMaterialKeys,
+            String[] keyMaterialKeyAlgs,
+            ContextParameters params) throws Exception {
+
+        KeyStore ts = null;     // trust store
+        KeyStore ks = null;     // key store
+        char passphrase[] = "passphrase".toCharArray();
+
+        // Generate certificate from cert string.
+        CertificateFactory cf = CertificateFactory.getInstance("X.509");
+
+        // Import the trused certs.
+        ByteArrayInputStream is;
+        if (trustedMaterials != null && trustedMaterials.length != 0) {
+            ts = KeyStore.getInstance("JKS");
+            ts.load(null, null);
+
+            Certificate[] trustedCert =
+                    new Certificate[trustedMaterials.length];
+            for (int i = 0; i < trustedMaterials.length; i++) {
+                String trustedCertStr = trustedMaterials[i];
+
+                is = new ByteArrayInputStream(trustedCertStr.getBytes());
+                try {
+                    trustedCert[i] = cf.generateCertificate(is);
+                } finally {
+                    is.close();
+                }
+
+                ts.setCertificateEntry("trusted-cert-" + i, trustedCert[i]);
+            }
+        }
+
+        // Import the key materials.
+        //
+        // Note that certification pathes bigger than one are not supported yet.
+        boolean hasKeyMaterials =
+            (keyMaterialCerts != null) && (keyMaterialCerts.length != 0) &&
+            (keyMaterialKeys != null) && (keyMaterialKeys.length != 0) &&
+            (keyMaterialKeyAlgs != null) && (keyMaterialKeyAlgs.length != 0) &&
+            (keyMaterialCerts.length == keyMaterialKeys.length) &&
+            (keyMaterialCerts.length == keyMaterialKeyAlgs.length);
+        if (hasKeyMaterials) {
+            ks = KeyStore.getInstance("JKS");
+            ks.load(null, null);
+
+            for (int i = 0; i < keyMaterialCerts.length; i++) {
+                String keyCertStr = keyMaterialCerts[i];
+
+                // generate the private key.
+                PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(
+                    Base64.getMimeDecoder().decode(keyMaterialKeys[i]));
+                KeyFactory kf =
+                    KeyFactory.getInstance(keyMaterialKeyAlgs[i]);
+                PrivateKey priKey = kf.generatePrivate(priKeySpec);
+
+                // generate certificate chain
+                is = new ByteArrayInputStream(keyCertStr.getBytes());
+                Certificate keyCert = null;
+                try {
+                    keyCert = cf.generateCertificate(is);
+                } finally {
+                    is.close();
+                }
+
+                Certificate[] chain = new Certificate[] { keyCert };
+
+                // import the key entry.
+                ks.setKeyEntry("cert-" + keyMaterialKeyAlgs[i],
+                        priKey, passphrase, chain);
+            }
+        }
+
+        // Create an SSLContext object.
+        TrustManagerFactory tmf =
+                TrustManagerFactory.getInstance(params.tmAlgorithm);
+        tmf.init(ts);
+
+        SSLContext context = SSLContext.getInstance(params.contextProtocol);
+        if (hasKeyMaterials && ks != null) {
+            KeyManagerFactory kmf =
+                    KeyManagerFactory.getInstance(params.kmAlgorithm);
+            kmf.init(ks, passphrase);
+
+            context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
+        } else {
+            context.init(null, tmf.getTrustManagers(), null);
+        }
+
+        return context;
+    }
+
+    /*
+     * =================================================
+     * Stuffs to boot up the client-server mode testing.
+     */
+    private Thread clientThread = null;
+    private Thread serverThread = null;
+    private volatile Exception serverException = null;
+    private volatile Exception clientException = null;
+
+    /*
+     * Should we run the client or server in a separate thread?
+     * Both sides can throw exceptions, but do you have a preference
+     * as to which side should be the main thread.
+     */
+    private static final boolean separateServerThread = false;
+
+    /*
+     * Boot up the testing, used to drive remainder of the test.
+     */
+    private void bootup() throws Exception {
+        Exception startException = null;
+        try {
+            if (separateServerThread) {
+                startServer(true);
+                startClient(false);
+            } else {
+                startClient(true);
+                startServer(false);
+            }
+        } catch (Exception e) {
+            startException = e;
+        }
+
+        /*
+         * Wait for other side to close down.
+         */
+        if (separateServerThread) {
+            if (serverThread != null) {
+                serverThread.join();
+            }
+        } else {
+            if (clientThread != null) {
+                clientThread.join();
+            }
+        }
+
+        /*
+         * When we get here, the test is pretty much over.
+         * Which side threw the error?
+         */
+        Exception local;
+        Exception remote;
+
+        if (separateServerThread) {
+            remote = serverException;
+            local = clientException;
+        } else {
+            remote = clientException;
+            local = serverException;
+        }
+
+        Exception exception = null;
+
+        /*
+         * Check various exception conditions.
+         */
+        if ((local != null) && (remote != null)) {
+            // If both failed, return the curthread's exception.
+            local.initCause(remote);
+            exception = local;
+        } else if (local != null) {
+            exception = local;
+        } else if (remote != null) {
+            exception = remote;
+        } else if (startException != null) {
+            exception = startException;
+        }
+
+        /*
+         * If there was an exception *AND* a startException,
+         * output it.
+         */
+        if (exception != null) {
+            if (exception != startException && startException != null) {
+                exception.addSuppressed(startException);
+            }
+            throw exception;
+        }
+
+        // Fall-through: no exception to throw!
+    }
+
+    private void startServer(boolean newThread) throws Exception {
+        if (newThread) {
+            serverThread = new Thread() {
+                @Override
+                public void run() {
+                    try {
+                        doServerSide();
+                    } catch (Exception e) {
+                        /*
+                         * Our server thread just died.
+                         *
+                         * Release the client, if not active already...
+                         */
+                        logException("Server died", e);
+                        serverException = e;
+                    }
+                }
+            };
+            serverThread.start();
+        } else {
+            try {
+                doServerSide();
+            } catch (Exception e) {
+                logException("Server failed", e);
+                serverException = e;
+            }
+        }
+    }
+
+    private void startClient(boolean newThread) throws Exception {
+        if (newThread) {
+            clientThread = new Thread() {
+                @Override
+                public void run() {
+                    try {
+                        doClientSide();
+                    } catch (Exception e) {
+                        /*
+                         * Our client thread just died.
+                         */
+                        logException("Client died", e);
+                        clientException = e;
+                    }
+                }
+            };
+            clientThread.start();
+        } else {
+            try {
+                doClientSide();
+            } catch (Exception e) {
+                logException("Client failed", e);
+                clientException = e;
+            }
+        }
+    }
+
+    private synchronized void logException(String prefix, Throwable cause) {
+        System.out.println(prefix + ": " + cause);
+        cause.printStackTrace(System.out);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/lib/testlibrary/CompilerUtils.java	Tue Jan 16 22:58:44 2018 -0800
@@ -0,0 +1,101 @@
+/*
+ * Copyright (c) 2015, 2017, 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.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import javax.tools.JavaCompiler;
+import javax.tools.StandardJavaFileManager;
+import javax.tools.StandardLocation;
+import javax.tools.ToolProvider;
+
+import jdk.testlibrary.OutputAnalyzer;
+import jdk.testlibrary.ProcessTools;
+
+/**
+ * This class consists exclusively of static utility methods for invoking the
+ * java compiler.
+ */
+
+public final class CompilerUtils {
+    private static final String TEST_JAVA_HOME = System.getProperty("test.jdk");
+    private static final String FS = File.separator;
+    private static final String JAVAC = TEST_JAVA_HOME + FS + "bin" + FS + "javac";
+
+    private CompilerUtils() { }
+
+    /**
+     * Compile all the java sources in {@code <source>/**} to
+     * {@code <destination>/**}. The destination directory will be created if
+     * it doesn't exist.
+     *
+     * All warnings/errors emitted by the compiler are output to System.out/err.
+     *
+     * @return true if the compilation is successful
+     *
+     * @throws IOException
+     *         if there is an I/O error scanning the source tree or
+     *         creating the destination directory
+     * @throws UnsupportedOperationException
+     *         if there is no system java compiler
+     */
+    public static boolean compile(Path source, Path destination, String ... options)
+        throws IOException
+    {
+        List<Path> sources
+            = Files.find(source, Integer.MAX_VALUE,
+                (file, attrs) -> (file.toString().endsWith(".java")))
+                .collect(Collectors.toList());
+
+        Files.createDirectories(destination);
+        List<String> opts = Arrays.asList(options);
+        List<String> compileargs = new ArrayList<String> ();
+        compileargs.add(JAVAC);
+        compileargs.add("-d");
+        compileargs.add(destination.toString());
+        for(String opt: opts) {
+            compileargs.add(opt);
+        }
+        for(Path p: sources) {
+            compileargs.add(p.toString());
+        }
+
+        OutputAnalyzer output = null;
+        try {
+            String[] sarr = compileargs.toArray(new String[0]);
+            output = ProcessTools.executeCommand(sarr);
+            output.shouldHaveExitValue(0);
+        } catch (Throwable t) {
+            throw new RuntimeException("Javac failed", t);
+        }
+
+        return true;
+    }
+}
--- a/test/lib/testlibrary/jdk/testlibrary/OutputAnalyzer.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/test/lib/testlibrary/jdk/testlibrary/OutputAnalyzer.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2015 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2017 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
@@ -369,7 +369,7 @@
      * - standard input produced by the process under test - standard output -
      * exit code Note: the command line is printed by the ProcessTools
      */
-    private OutputAnalyzer reportDiagnosticSummary() {
+    public OutputAnalyzer reportDiagnosticSummary() {
         String msg = " stdout: [" + stdout + "];\n" + " stderr: [" + stderr
                 + "]\n" + " exitValue = " + getExitValue() + "\n";
 
--- a/test/sun/net/www/http/HttpClient/B8025710.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/test/sun/net/www/http/HttpClient/B8025710.java	Tue Jan 16 22:58:44 2018 -0800
@@ -37,6 +37,7 @@
  * @test
  * @bug 8025710
  * @summary Proxied https connection reuse by HttpClient can send CONNECT to the server
+ * @run main/othervm B8025710
  */
 public class B8025710 {
 
@@ -47,6 +48,9 @@
     private static final String passphrase = "passphrase";
 
     public static void main(String[] args) throws Exception {
+        // test uses legacy MD5 based cert
+        Security.setProperty("jdk.certpath.disabledAlgorithms", "");
+        Security.setProperty("jdk.tls.disabledAlgorithms", "");
         new B8025710().runTest();
 
         if (connectInServer.get())
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/sun/security/pkcs11/KeyAgreement/SupportedDHKeys.java	Tue Jan 16 22:58:44 2018 -0800
@@ -0,0 +1,131 @@
+/*
+ * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * @test
+ * @bug 8072452
+ * @summary Support DHE sizes up to 8192-bits and DSA sizes up to 3072-bits
+ * @library ..
+ * @run main/othervm SupportedDHKeys
+ */
+
+import java.math.BigInteger;
+
+import java.security.*;
+import javax.crypto.*;
+import javax.crypto.interfaces.*;
+import javax.crypto.spec.*;
+
+public class SupportedDHKeys extends PKCS11Test {
+
+    /*
+     * Sizes and values for various lengths.
+     */
+    private enum SupportedKeySize {
+        dhp512(512),   dhp768(768),    dhp832(832),
+        dhp1024(1024), dhp1536(1536),  dhp2048(2048);
+
+        // the underlying pkcs11 may not support the following sizes yet
+        //
+        // dhp3072(3072), dhp4096(4096),  dhp6144(6144),
+        // dhp8192(8192);
+
+        final int primeSize;
+
+        SupportedKeySize(int primeSize) {
+            this.primeSize = primeSize;
+        }
+    }
+
+    @Override
+    public void main(Provider provider) throws Exception {
+        if (provider.getService("KeyPairGenerator", "DiffieHellman") == null) {
+            System.out.println("No support of DH KeyPairGenerator, skipping");
+            return;
+        }
+
+        for (SupportedKeySize keySize : SupportedKeySize.values()) {
+            System.out.println("Checking " + keySize.primeSize + " ...");
+            KeyPairGenerator kpg =
+                    KeyPairGenerator.getInstance("DiffieHellman", provider);
+            kpg.initialize(keySize.primeSize);
+            KeyPair kp = kpg.generateKeyPair();
+            checkKeyPair(kp, keySize.primeSize, provider);
+
+            DHPublicKey publicKey = (DHPublicKey)kp.getPublic();
+            BigInteger p = publicKey.getParams().getP();
+            BigInteger g = publicKey.getParams().getG();
+            kpg.initialize(new DHParameterSpec(p, g));
+            kp = kpg.generateKeyPair();
+            checkKeyPair(kp, keySize.primeSize, provider);
+        }
+    }
+
+    private static void checkKeyPair(KeyPair kp, int pSize,
+                Provider provider) throws Exception {
+
+        DHPrivateKey privateKey = (DHPrivateKey)kp.getPrivate();
+        BigInteger p = privateKey.getParams().getP();
+        if (p.bitLength() != pSize) {
+            throw new Exception(
+                "Invalid modulus size: " + p.bitLength() + "/" + pSize);
+        }
+
+        // System.out.println("P(" + pSize + "): " + p.toString());
+        if (!p.isProbablePrime(128)) {
+            throw new Exception("Good luck, the modulus is composite!");
+        }
+
+        DHPublicKey publicKey = (DHPublicKey)kp.getPublic();
+        p = publicKey.getParams().getP();
+        if (p.bitLength() != pSize) {
+            throw new Exception(
+                "Invalid modulus size: " + p.bitLength() + "/" + pSize);
+        }
+
+        BigInteger leftOpen = BigInteger.ONE;
+        BigInteger rightOpen = p.subtract(BigInteger.ONE);
+
+        // ignore the private key range checking on Solaris at present
+        if (provider.getName().equals("SunPKCS11-Solaris") &&
+                !System.getProperty("os.name").equals("SunOS")) {
+            BigInteger x = privateKey.getX();
+            if ((x.compareTo(leftOpen) <= 0) ||
+                    (x.compareTo(rightOpen) >= 0)) {
+                throw new Exception(
+                    "X outside range [2, p - 2]:  x: " + x + " p: " + p);
+            }
+        }
+
+        BigInteger y = publicKey.getY();
+        if ((y.compareTo(leftOpen) <= 0) ||
+                (y.compareTo(rightOpen) >= 0)) {
+            throw new Exception(
+                "Y outside range [2, p - 2]:  y: " + y + " p: " + p);
+        }
+    }
+
+    public static void main(String[] args) throws Exception {
+        main(new SupportedDHKeys());
+    }
+}
--- a/test/sun/security/pkcs11/KeyAgreement/TestDH.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/test/sun/security/pkcs11/KeyAgreement/TestDH.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, 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
@@ -27,6 +27,8 @@
  * @summary Verify that DH works properly
  * @author Andreas Sterbenz
  * @library ..
+ * @run main/othervm -Djdk.crypto.KeyAgreement.legacyKDF=true TestDH
+ * @run main/othervm -Djdk.crypto.KeyAgreement.legacyKDF=true TestDH sm
  */
 
 import java.io.*;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/sun/security/pkcs11/KeyAgreement/UnsupportedDHKeys.java	Tue Jan 16 22:58:44 2018 -0800
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * @test
+ * @bug 8072452
+ * @summary Support DHE sizes up to 8192-bits and DSA sizes up to 3072-bits
+ * @library ..
+ * @run main/othervm UnsupportedDHKeys
+ */
+
+import java.math.BigInteger;
+
+import java.security.*;
+import javax.crypto.*;
+import javax.crypto.interfaces.*;
+import javax.crypto.spec.*;
+
+public class UnsupportedDHKeys extends PKCS11Test {
+
+    /*
+     * Sizes and values for various lengths.
+     */
+    private enum UnsupportedKeySize {
+        // not multiple of 64
+        dhp513(513),    dhp769(769),    dhp895(895),
+        dhp1023(1023),  dhp1535(1535),  dhp2047(2047),
+
+        // unsupported
+        dhp2176(2176),  dhp3008(3008),  dhp4032(4032),
+        dhp5120(5120),  dhp6400(6400),  dhp7680(7680),
+        dhp8191(8191),  dhp8128(8128),  dhp8260(8260);
+
+        final int primeSize;
+
+        UnsupportedKeySize(int primeSize) {
+            this.primeSize = primeSize;
+        }
+    }
+
+    @Override
+    public void main(Provider provider) throws Exception {
+        if (provider.getService("KeyPairGenerator", "DiffieHellman") == null) {
+            System.out.println("No supported of DH KeyPairGenerator, skipping");
+            return;
+        }
+
+        for (UnsupportedKeySize keySize : UnsupportedKeySize.values()) {
+            try {
+                System.out.println("Checking " + keySize.primeSize + " ...");
+                KeyPairGenerator kpg =
+                        KeyPairGenerator.getInstance("DiffieHellman", provider);
+                kpg.initialize(keySize.primeSize);
+
+                throw new Exception("Should not support " + keySize.primeSize);
+            } catch (InvalidParameterException ipe) {
+                System.out.println("\tOk, unsupported");
+            }
+        }
+    }
+
+    public static void main(String[] args) throws Exception {
+        main(new UnsupportedDHKeys());
+    }
+}
--- a/test/sun/security/pkcs11/KeyPairGenerator/TestDH2048.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/test/sun/security/pkcs11/KeyPairGenerator/TestDH2048.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2017, 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
@@ -23,8 +23,8 @@
 
 /**
  * @test
- * @bug 7196382
- * @summary Ensure that 2048-bit DH key pairs can be generated
+ * @bug 7196382 8072452
+ * @summary Ensure that DH key pairs can be generated for 512 - 8192 bits
  * @author Valerie Peng
  * @library ..
  */
@@ -53,11 +53,31 @@
             return;
         }
         KeyPairGenerator kpg = KeyPairGenerator.getInstance("DH", p);
-        kpg.initialize(2048);
+        kpg.initialize(512);
         KeyPair kp1 = kpg.generateKeyPair();
-        checkUnsupportedKeySize(kpg, 1536);
-        checkUnsupportedKeySize(kpg, 2176);
-        checkUnsupportedKeySize(kpg, 3072);
+
+        int[] test_values = {768, 1024, 1536, 2048, 3072, 4096, 6144, 8192};
+        for (int i : test_values)
+        try {
+            kpg.initialize(i);
+            kp1 = kpg.generateKeyPair();
+        } catch (InvalidParameterException ipe) {
+            // NSS (as of version 3.13) has a hard coded maximum limit
+            // of 2236 or 3072 bits for DHE keys.
+            // SunPKCS11-Solaris has limit of 4096 on older systems
+            String prov = p.getName();
+            System.out.println(i + "-bit DH key pair generation: " + ipe);
+            if ((prov.equals("SunPKCS11-NSS") && i > 2048) ||
+                (prov.equals("SunPKCS11-Solaris") && i > 4096)) {
+                // OK
+            } else {
+                throw ipe;
+            }
+        }
+
+        // key size must be multiples of 64 though
+        checkUnsupportedKeySize(kpg, 2048 + 63);
+        checkUnsupportedKeySize(kpg, 3072 + 32);
     }
 
     public static void main(String[] args) throws Exception {
--- a/test/sun/security/pkcs11/PKCS11Test.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/test/sun/security/pkcs11/PKCS11Test.java	Tue Jan 16 22:58:44 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, 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
@@ -509,6 +509,8 @@
             PKCS11_BASE + "/nss/lib/windows-i586/".replace('/', SEP)});
         osMap.put("Windows-amd64-64", new String[]{
             PKCS11_BASE + "/nss/lib/windows-amd64/".replace('/', SEP)});
+        osMap.put("MacOSX-x86_64-64", new String[]{
+            PKCS11_BASE + "/nss/lib/macosx-x86_64/"});
     }
 
     private final static char[] hexDigits = "0123456789abcdef".toCharArray();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/sun/security/provider/DSA/SupportedDSAParamGen.java	Tue Jan 16 22:58:44 2018 -0800
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8072452
+ * @key intermittent
+ * @summary Support DHE sizes up to 8192-bits and DSA sizes up to 3072-bits
+ * @run main/timeout=300 SupportedDSAParamGen 1024 160
+ * @run main/timeout=300 SupportedDSAParamGen 2048 224
+ * @run main/timeout=300 SupportedDSAParamGen 2048 256
+ * @run main/timeout=450 SupportedDSAParamGen 3072 256
+ */
+import java.security.*;
+import java.security.spec.*;
+import java.security.interfaces.*;
+
+public class SupportedDSAParamGen {
+
+    public static void main(String[] args) throws Exception {
+        AlgorithmParameterGenerator apg =
+            AlgorithmParameterGenerator.getInstance("DSA", "SUN");
+
+        DSAGenParameterSpec spec = new DSAGenParameterSpec(
+                Integer.valueOf(args[0]).intValue(),
+                Integer.valueOf(args[1]).intValue());
+
+        System.out.println("Generating (" + spec.getPrimePLength() +
+                ", " + spec.getSubprimeQLength() + ") DSA Parameters");
+        long start = System.currentTimeMillis();
+        apg.init(spec, null);
+        AlgorithmParameters param = apg.generateParameters();
+        long stop = System.currentTimeMillis();
+        System.out.println("Time: " + (stop - start) + " ms.");
+        checkParamStrength(param, spec);
+    }
+
+    private static void checkParamStrength(AlgorithmParameters param,
+            DSAGenParameterSpec genParam) throws Exception {
+
+        String algo = param.getAlgorithm();
+        if (!algo.equalsIgnoreCase("DSA")) {
+            throw new Exception("Unexpected type of parameters: " + algo);
+        }
+
+        DSAParameterSpec spec = param.getParameterSpec(DSAParameterSpec.class);
+        int valueL = spec.getP().bitLength();
+        int strength = genParam.getPrimePLength();
+        if (strength != valueL) {
+            System.out.println(
+                    "P: Expected " + strength + " but actual " + valueL);
+            throw new Exception("Wrong P strength");
+        }
+
+        int valueN = spec.getQ().bitLength();
+        strength = genParam.getSubprimeQLength();
+        if (strength != valueN) {
+            System.out.println(
+                    "Q: Expected " + strength + " but actual " + valueN);
+            throw new Exception("Wrong Q strength");
+        }
+    }
+}
--- a/test/sun/security/provider/DSA/TestKeyPairGenerator.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/test/sun/security/provider/DSA/TestKeyPairGenerator.java	Tue Jan 16 22:58:44 2018 -0800
@@ -23,15 +23,18 @@
 
 /*
  * @test
- * @bug 4800108 8181048
- * @summary verify that precomputed DSA parameters are always used (512, 768, 1024, 2048 bit)
+ * @bug 4800108 8181048 8072452
+ * @summary verify that precomputed DSA parameters are always used (512, 768,
+ *          1024, 2048, 3072 bit)
  * @run main/othervm/timeout=15 TestKeyPairGenerator
  */
 
-// this fix is really a performance fix, so this test is not foolproof
-// without it, it will take a minute or more (unless you have a very fast machine)
-// with the fix, the test should complete in <2 seconds
-// use 15 second timeout to leave some room
+//
+// This fix is really a performance fix, so this test is not foolproof.
+// Without the precomputed parameters, it will take a minute or more
+// (unless you have a very fast machine).  With the fix, the test should
+// complete in less than 2 seconds.  Use 15 second timeout to leave some room.
+//
 
 import java.security.*;
 import java.security.interfaces.*;
@@ -79,8 +82,11 @@
         kp = kpg.generateKeyPair();
         checkKeyLength(kp, 2048);
 
+        kpg.initialize(3072);
+        kp = kpg.generateKeyPair();
+        checkKeyLength(kp, 3072);
+
         long stop = System.currentTimeMillis();
         System.out.println("Time: " + (stop - start) + " ms.");
     }
-
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/sun/security/ssl/DHKeyExchange/LegacyDHEKeyExchange.java	Tue Jan 16 22:58:44 2018 -0800
@@ -0,0 +1,325 @@
+/*
+ * Copyright (c) 2017, 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.
+ */
+
+// SunJSSE does not support dynamic system properties, no way to re-use
+// system properties in samevm/agentvm mode.
+
+/*
+ * @test
+ * @bug 8148108
+ * @summary Disable Diffie-Hellman keys less than 1024 bits
+ * @run main/othervm -Djdk.tls.ephemeralDHKeySize=legacy LegacyDHEKeyExchange
+ */
+
+import java.io.*;
+import javax.net.ssl.*;
+
+public class LegacyDHEKeyExchange {
+
+    /*
+     * =============================================================
+     * Set the various variables needed for the tests, then
+     * specify what tests to run on each side.
+     */
+
+    /*
+     * Should we run the client or server in a separate thread?
+     * Both sides can throw exceptions, but do you have a preference
+     * as to which side should be the main thread.
+     */
+    static boolean separateServerThread = false;
+
+    /*
+     * Where do we find the keystores?
+     */
+    static String pathToStores = "../etc";
+    static String keyStoreFile = "keystore";
+    static String trustStoreFile = "truststore";
+    static String passwd = "passphrase";
+
+    /*
+     * Is the server ready to serve?
+     */
+    volatile static boolean serverReady = false;
+
+    /*
+     * Turn on SSL debugging?
+     */
+    static boolean debug = false;
+
+    /*
+     * If the client or server is doing some kind of object creation
+     * that the other side depends on, and that thread prematurely
+     * exits, you may experience a hang.  The test harness will
+     * terminate all hung threads after its timeout has expired,
+     * currently 3 minutes by default, but you might try to be
+     * smart about it....
+     */
+
+    /*
+     * Define the server side of the test.
+     *
+     * If the server prematurely exits, serverReady will be set to true
+     * to avoid infinite hangs.
+     */
+    void doServerSide() throws Exception {
+        SSLServerSocketFactory sslssf =
+            (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
+        SSLServerSocket sslServerSocket =
+            (SSLServerSocket) sslssf.createServerSocket(serverPort);
+
+        serverPort = sslServerSocket.getLocalPort();
+
+        /*
+         * Signal Client, we're ready for his connect.
+         */
+        serverReady = true;
+
+        try (SSLSocket sslSocket = (SSLSocket)sslServerSocket.accept()) {
+            InputStream sslIS = sslSocket.getInputStream();
+            OutputStream sslOS = sslSocket.getOutputStream();
+
+            sslIS.read();
+            sslOS.write(85);
+            sslOS.flush();
+
+            throw new Exception(
+                "Legacy DH keys (< 1024) should be restricted");
+        } catch (SSLHandshakeException she) {
+            // ignore, client should terminate the connection
+        } finally {
+            sslServerSocket.close();
+        }
+    }
+
+    /*
+     * Define the client side of the test.
+     *
+     * If the server prematurely exits, serverReady will be set to true
+     * to avoid infinite hangs.
+     */
+    void doClientSide() throws Exception {
+
+        /*
+         * Wait for server to get started.
+         */
+        while (!serverReady) {
+            Thread.sleep(50);
+        }
+
+        SSLSocketFactory sslsf =
+            (SSLSocketFactory) SSLSocketFactory.getDefault();
+        SSLSocket sslSocket = (SSLSocket)
+            sslsf.createSocket("localhost", serverPort);
+
+        String[] suites = new String [] {"TLS_DHE_RSA_WITH_AES_128_CBC_SHA"};
+        sslSocket.setEnabledCipherSuites(suites);
+
+        try {
+            InputStream sslIS = sslSocket.getInputStream();
+            OutputStream sslOS = sslSocket.getOutputStream();
+
+            sslOS.write(280);
+            sslOS.flush();
+            sslIS.read();
+
+            throw new Exception("Legacy DH keys (< 1024) should be restricted");
+        } catch (SSLHandshakeException she) {
+            // ignore, should be caused by algorithm constraints
+        } finally {
+            sslSocket.close();
+        }
+    }
+
+    /*
+     * =============================================================
+     * The remainder is just support stuff
+     */
+
+    // use any free port by default
+    volatile int serverPort = 0;
+
+    volatile Exception serverException = null;
+    volatile Exception clientException = null;
+
+    public static void main(String[] args) throws Exception {
+        String keyFilename =
+            System.getProperty("test.src", ".") + "/" + pathToStores +
+                "/" + keyStoreFile;
+        String trustFilename =
+            System.getProperty("test.src", ".") + "/" + pathToStores +
+                "/" + trustStoreFile;
+
+        System.setProperty("javax.net.ssl.keyStore", keyFilename);
+        System.setProperty("javax.net.ssl.keyStorePassword", passwd);
+        System.setProperty("javax.net.ssl.trustStore", trustFilename);
+        System.setProperty("javax.net.ssl.trustStorePassword", passwd);
+
+        if (debug) {
+            System.setProperty("javax.net.debug", "all");
+        }
+
+        /*
+         * Start the tests.
+         */
+        new LegacyDHEKeyExchange();
+    }
+
+    Thread clientThread = null;
+    Thread serverThread = null;
+
+    /*
+     * Primary constructor, used to drive remainder of the test.
+     *
+     * Fork off the other side, then do your work.
+     */
+    LegacyDHEKeyExchange() throws Exception {
+        Exception startException = null;
+        try {
+            if (separateServerThread) {
+                startServer(true);
+                startClient(false);
+            } else {
+                startClient(true);
+                startServer(false);
+            }
+        } catch (Exception e) {
+            startException = e;
+        }
+
+        /*
+         * Wait for other side to close down.
+         */
+        if (separateServerThread) {
+            if (serverThread != null) {
+                serverThread.join();
+            }
+        } else {
+            if (clientThread != null) {
+                clientThread.join();
+            }
+        }
+
+        /*
+         * When we get here, the test is pretty much over.
+         * Which side threw the error?
+         */
+        Exception local;
+        Exception remote;
+
+        if (separateServerThread) {
+            remote = serverException;
+            local = clientException;
+        } else {
+            remote = clientException;
+            local = serverException;
+        }
+
+        Exception exception = null;
+
+        /*
+         * Check various exception conditions.
+         */
+        if ((local != null) && (remote != null)) {
+            // If both failed, return the curthread's exception.
+            local.initCause(remote);
+            exception = local;
+        } else if (local != null) {
+            exception = local;
+        } else if (remote != null) {
+            exception = remote;
+        } else if (startException != null) {
+            exception = startException;
+        }
+
+        /*
+         * If there was an exception *AND* a startException,
+         * output it.
+         */
+        if (exception != null) {
+            if (exception != startException && startException != null) {
+                exception.addSuppressed(startException);
+            }
+            throw exception;
+        }
+
+        // Fall-through: no exception to throw!
+    }
+
+    void startServer(boolean newThread) throws Exception {
+        if (newThread) {
+            serverThread = new Thread() {
+                @Override
+                public void run() {
+                    try {
+                        doServerSide();
+                    } catch (Exception e) {
+                        /*
+                         * Our server thread just died.
+                         *
+                         * Release the client, if not active already...
+                         */
+                        System.err.println("Server died...");
+                        serverReady = true;
+                        serverException = e;
+                    }
+                }
+            };
+            serverThread.start();
+        } else {
+            try {
+                doServerSide();
+            } catch (Exception e) {
+                serverException = e;
+            } finally {
+                serverReady = true;
+            }
+        }
+    }
+
+    void startClient(boolean newThread) throws Exception {
+        if (newThread) {
+            clientThread = new Thread() {
+                @Override
+                public void run() {
+                    try {
+                        doClientSide();
+                    } catch (Exception e) {
+                        /*
+                         * Our client thread just died.
+                         */
+                        System.err.println("Client died...");
+                        clientException = e;
+                    }
+                }
+            };
+            clientThread.start();
+        } else {
+            try {
+                doClientSide();
+            } catch (Exception e) {
+                clientException = e;
+            }
+        }
+    }
+}
--- a/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/ClientHandshaker/RSAExport.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/ClientHandshaker/RSAExport.java	Tue Jan 16 22:58:44 2018 -0800
@@ -419,6 +419,7 @@
         // reset the security property to make sure that the algorithms
         // and keys used in this test are not disabled.
         Security.setProperty("jdk.certpath.disabledAlgorithms", "MD2");
+        Security.setProperty("jdk.tls.disabledAlgorithms", "MD2");
 
         if (debug)
             System.setProperty("javax.net.debug", "all");
--- a/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/DHKeyExchange/DHEKeySizing.java	Mon Jan 08 22:36:23 2018 -0800
+++ b/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/DHKeyExchange/DHEKeySizing.java	Tue Jan 16 22:58:44 2018 -0800
@@ -31,34 +31,34 @@
  * @bug 6956398
  * @summary make ephemeral DH key match the length of the certificate key
  * @run main/othervm
- *      DHEKeySizing SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA true 1255 75
+ *      DHEKeySizing SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA true 1259 75
  * @run main/othervm -Djdk.tls.ephemeralDHKeySize=matched
- *      DHEKeySizing SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA true 1255 75
+ *      DHEKeySizing SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA true 1259 75
  * @run main/othervm -Djdk.tls.ephemeralDHKeySize=legacy
- *      DHEKeySizing SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA true 1255 75
+ *      DHEKeySizing SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA true 1259 75
  * @run main/othervm -Djdk.tls.ephemeralDHKeySize=1024
- *      DHEKeySizing SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA true 1255 75
+ *      DHEKeySizing SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA true 1259 75
  *
  * @run main/othervm
- *      DHEKeySizing SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA true 229 75
+ *      DHEKeySizing SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA true 233 75
  *
  * @run main/othervm
- *      DHEKeySizing TLS_DHE_RSA_WITH_AES_128_CBC_SHA  false 1383 139
+ *      DHEKeySizing TLS_DHE_RSA_WITH_AES_128_CBC_SHA  false 1387 139
  * @run main/othervm -Djdk.tls.ephemeralDHKeySize=legacy
- *      DHEKeySizing TLS_DHE_RSA_WITH_AES_128_CBC_SHA  false 1319 107
+ *      DHEKeySizing TLS_DHE_RSA_WITH_AES_128_CBC_SHA  false 1323 107
  * @run main/othervm -Djdk.tls.ephemeralDHKeySize=matched
- *      DHEKeySizing TLS_DHE_RSA_WITH_AES_128_CBC_SHA  false 1639 267
+ *      DHEKeySizing TLS_DHE_RSA_WITH_AES_128_CBC_SHA  false 1643 267
  * @run main/othervm -Djdk.tls.ephemeralDHKeySize=1024
- *      DHEKeySizing TLS_DHE_RSA_WITH_AES_128_CBC_SHA  false 1383 139
+ *      DHEKeySizing TLS_DHE_RSA_WITH_AES_128_CBC_SHA  false 1387 139
  *
  * @run main/othervm
- *      DHEKeySizing SSL_DH_anon_WITH_RC4_128_MD5  false 357 139
+ *      DHEKeySizing SSL_DH_anon_WITH_RC4_128_MD5  false 361 139
  * @run main/othervm -Djdk.tls.ephemeralDHKeySize=legacy
- *      DHEKeySizing SSL_DH_anon_WITH_RC4_128_MD5  false 293 107
+ *      DHEKeySizing SSL_DH_anon_WITH_RC4_128_MD5  false 297 107
  * @run main/othervm -Djdk.tls.ephemeralDHKeySize=matched
- *      DHEKeySizing SSL_DH_anon_WITH_RC4_128_MD5  false 357 139
+ *      DHEKeySizing SSL_DH_anon_WITH_RC4_128_MD5  false 361 139
  * @run main/othervm -Djdk.tls.ephemeralDHKeySize=1024
- *      DHEKeySizing SSL_DH_anon_WITH_RC4_128_MD5  false 357 139
+ *      DHEKeySizing SSL_DH_anon_WITH_RC4_128_MD5  false 361 139
  */
 
 /*
@@ -90,10 +90,10 @@
  * Here is a summary of the record length in the test case.
  *
  *            |  ServerHello Series  |  ClientKeyExchange | ServerHello Anon
- *   512-bit  |          1255 bytes  |           75 bytes |        229 bytes
- *   768-bit  |          1319 bytes  |          107 bytes |        293 bytes
- *  1024-bit  |          1383 bytes  |          139 bytes |        357 bytes
- *  2048-bit  |          1639 bytes  |          267 bytes |        357 bytes
+ *   512-bit  |          1259 bytes  |           75 bytes |        233 bytes
+ *   768-bit  |          1323 bytes  |          107 bytes |        297 bytes
+ *  1024-bit  |          1387 bytes  |          139 bytes |        361 bytes
+ *  2048-bit  |          1643 bytes  |          267 bytes |        361 bytes
  */
 
 import javax.net.ssl.*;