Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix CharArraysTests.testConstantTimeEquals() #47346

Merged
merged 1 commit into from
Oct 1, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@

import java.nio.charset.StandardCharsets;

import static org.hamcrest.Matchers.is;

public class CharArraysTests extends ESTestCase {

public void testCharsToBytes() {
Expand Down Expand Up @@ -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();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't have strong feeling about it, but might be more straight forward to make sure this never happens on line 70 above.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well, I think this method must support empty strings/char arrays so... :)

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) {
Expand Down