Work around JDK bug that can cause SCRAM-SHA-1 authentication to intermittently fail, by synchronizing on the SecretKey in order to avoid premature finalization.
See for the bug report and for the suggested workaround
@@ -21,6 +21,7 @@ import com.mongodb.ServerAddress;
import org.bson.internal.Base64;
import javax.crypto.Mac;
+import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
@@ -229,7 +230,13 @@ class ScramSha1Authenticator extends SaslAuthenticator {
}
try {
- return keyFactory.generateSecret(spec).getEncoded();
+ SecretKey secretKey = keyFactory.generateSecret(spec);
+ // Workaround for https://bugs.openjdk.java.net/browse/JDK-8191177, as suggested in
+ // https://bugs.openjdk.java.net/browse/JDK-8055183
+ //noinspection SynchronizationOnLocalVariableOrMethodParameter
+ synchronized (secretKey) {
+ return secretKey.getEncoded();
+ }
}
catch (InvalidKeySpecException e) {
throw new SaslException("Invalid key spec for PBKDC2WithHmacSHA1.", e);
