Skip to content

Commit

Permalink
digest resets after getting value, so can't call it more than once. (#…
Browse files Browse the repository at this point in the history
scottf authored Mar 8, 2023
1 parent a367502 commit b2ff1bc
Showing 2 changed files with 22 additions and 2 deletions.
12 changes: 10 additions & 2 deletions src/main/java/io/nats/client/support/Digester.java
Original file line number Diff line number Diff line change
@@ -28,6 +28,7 @@ public class Digester {
private final Charset stringCharset;
private final Base64.Encoder encoder;
private final MessageDigest digest;
private String digestValue;

public Digester() throws NoSuchAlgorithmException {
this(null, null, null);
@@ -50,21 +51,25 @@ public Digester(String digestAlgorithm, Charset stringCharset, Base64.Encoder en

public Digester update(String input) {
digest.update(input.getBytes(stringCharset));
digestValue = null;
return this;
}

public Digester update(byte[] input) {
digest.update(input);
digestValue = null;
return this;
}

public Digester update(byte[] input, int offset, int len) {
digest.update(input, offset, len);
digestValue = null;
return this;
}

public Digester reset() {
digest.reset();
digestValue = null;
return this;
}

@@ -81,11 +86,14 @@ public Digester reset(byte[] input, int offset, int len) {
}

public String getDigestValue() {
return encoder.encodeToString(digest.digest());
if (digestValue == null) {
digestValue = encoder.encodeToString(digest.digest());
}
return digestValue;
}

public String getDigestEntry() {
return digest.getAlgorithm() + "=" + encoder.encodeToString(digest.digest());
return digest.getAlgorithm() + "=" + getDigestValue();
}

public boolean matches(String digestEntry) {
12 changes: 12 additions & 0 deletions src/test/java/io/nats/client/support/DigesterTests.java
Original file line number Diff line number Diff line change
@@ -120,5 +120,17 @@ public void testDigesterData() throws NoSuchAlgorithmException {
s = ResourceUtils.dataAsString("digester_test_bytes_100000.txt");
d.reset(s);
assertEquals("yan7pwBVnC1yORqqgBfd64_qAw6q9fNA60_KRiMMooE=", d.getDigestValue());

d.reset("a");
assertEquals("ypeBEsobvcr6wjGzmiPcTaeG7_gUfE5yuYB3ha_uSLs=", d.getDigestValue());

d.reset("aa");
assertEquals("lhtt0-3jy47LqsvWjeBAzXjrLtWIkTDM60xJJo6k1QY=", d.getDigestValue());

d.reset("aaa");
assertEquals("mDSHbc-wXLFnpcJJU-uljErImxrfV_KPL50JrxB-6PA=", d.getDigestValue());

d.reset("aaaa");
assertEquals("Yb5VqOL2tOFyM4vd8YTW2-4pyYhT4KBIXs7n8nua8LQ=", d.getDigestValue());
}
}

0 comments on commit b2ff1bc

Please sign in to comment.