From 892c9b422d188bf447917dc4cfbecacc0bbf4839 Mon Sep 17 00:00:00 2001 From: Tanguy Leroux Date: Tue, 1 Oct 2019 11:30:04 +0200 Subject: [PATCH] Fix CharArraysTests.testConstantTimeEquals() --- .../org/elasticsearch/common/CharArraysTests.java | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/libs/core/src/test/java/org/elasticsearch/common/CharArraysTests.java b/libs/core/src/test/java/org/elasticsearch/common/CharArraysTests.java index a3f964bc14cda..9cedac763e29c 100644 --- a/libs/core/src/test/java/org/elasticsearch/common/CharArraysTests.java +++ b/libs/core/src/test/java/org/elasticsearch/common/CharArraysTests.java @@ -23,6 +23,8 @@ import java.nio.charset.StandardCharsets; +import static org.hamcrest.Matchers.is; + public class CharArraysTests extends ESTestCase { public void testCharsToBytes() { @@ -70,10 +72,12 @@ public void testConstantTimeEquals() { assertTrue(CharArrays.constantTimeEquals(value.toCharArray(), value.toCharArray())); // we want a different string, so ensure the first character is different, but the same overall length - final String other = new String( - randomAlphaOfLengthNotBeginningWith(value.substring(0, 1), value.length(), value.length())); - assertFalse("value: " + value + ", other: " + other, CharArrays.constantTimeEquals(value, other)); - assertFalse(CharArrays.constantTimeEquals(value.toCharArray(), other.toCharArray())); + final int length = value.length(); + final String other = length > 0 ? new String(randomAlphaOfLengthNotBeginningWith(value.substring(0, 1), length, length)) : ""; + final boolean expectedEquals = length == 0; + + assertThat("value: " + value + ", other: " + other, CharArrays.constantTimeEquals(value, other), is(expectedEquals)); + assertThat(CharArrays.constantTimeEquals(value.toCharArray(), other.toCharArray()), is(expectedEquals)); } private char[] randomAlphaOfLengthNotBeginningWith(String undesiredPrefix, int min, int max) {