Skip to content
Open
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
7 changes: 5 additions & 2 deletions client/src/main/java/org/asynchttpclient/Realm.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@

import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;

import static java.nio.charset.StandardCharsets.ISO_8859_1;
import static java.nio.charset.StandardCharsets.UTF_8;
Expand Down Expand Up @@ -283,6 +283,9 @@ public enum AuthScheme {
*/
public static class Builder {

// cnonce must be unpredictable (RFC 7616 section 3.3), like the NTLM and SCRAM nonces
private static final SecureRandom CNONCE_RANDOM = new SecureRandom();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Don't share one static SecureRandom; use a ThreadLocal. newCnonce runs on Netty event-loop threads (digest header build + 401/407 interceptors), and SecureRandom#nextBytes locks internally, so a single shared instance makes all event loops queue on one lock. ThreadLocalRandom had no such lock. ScramEngine already handles this the right way:

private static final ThreadLocal<SecureRandom> CNONCE_RANDOM = ThreadLocal.withInitial(SecureRandom::new);

and in newCnonce:

CNONCE_RANDOM.get().nextBytes(b);


private final @Nullable String principal;
private final @Nullable String password;
private @Nullable AuthScheme scheme;
Expand Down Expand Up @@ -610,7 +613,7 @@ public Builder parseProxyAuthenticateHeader(String headerLine) {

private void newCnonce(MessageDigest md) {
byte[] b = new byte[8];
ThreadLocalRandom.current().nextBytes(b);
CNONCE_RANDOM.nextBytes(b);
byte[] full = md.digest(b);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

the md.digest(b) step is now pointless. The 8 bytes are already cryptographically random, so hashing them and trimming back to 8 bytes adds nothing. The method can just be:

private void newCnonce() {
    byte[] b = new byte[8];
    CNONCE_RANDOM.get().nextBytes(b);
    cnonce = toHexString(b);
}

Same 16-hex-char cnonce. This is safe because pooledMessageDigest already resets the digest before build() gets it, so nothing downstream depends on the digest(b) call.

// trim to first 8 bytes → 16 hex chars
byte[] small = Arrays.copyOf(full, Math.min(8, full.length));
Expand Down
Loading