Skip to content

Fixed thread-safety issue of MessageDigest #817

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

Merged
merged 1 commit into from
Apr 4, 2022
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 @@ -60,7 +60,7 @@ public abstract class BasePersistenceStore implements PersistenceStore {
protected boolean payloadValidationEnabled = false;
private Expression<JsonNode> validationKeyJMESPath;
private boolean throwOnNoIdempotencyKey = false;
private MessageDigest hashAlgorithm;
private String hashFunctionName;

/**
* Initialize the base persistence layer from the configuration settings
Expand Down Expand Up @@ -95,17 +95,7 @@ public void configure(IdempotencyConfig config, String functionName) {
cache = new LRUCache<>(config.getLocalCacheMaxItems());
}
expirationInSeconds = config.getExpirationInSeconds();

try {
hashAlgorithm = MessageDigest.getInstance(config.getHashFunction());
} catch (NoSuchAlgorithmException e) {
LOG.warn("Error instantiating {} hash function, trying with MD5", config.getHashFunction());
try {
hashAlgorithm = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException ex) {
throw new RuntimeException("Unable to instantiate MD5 digest", ex);
}
}
hashFunctionName = config.getHashFunction();
configured = true;
}

Expand Down Expand Up @@ -275,10 +265,27 @@ String generateHash(JsonNode data) {
} else if (data.isBoolean()) {
node = data.asBoolean();
} else node = data; // anything else

MessageDigest hashAlgorithm = getHashAlgorithm();
byte[] digest = hashAlgorithm.digest(node.toString().getBytes(StandardCharsets.UTF_8));
return String.format("%032x", new BigInteger(1, digest));
}

private MessageDigest getHashAlgorithm() {
MessageDigest hashAlgorithm;
try {
hashAlgorithm = MessageDigest.getInstance(hashFunctionName);
} catch (NoSuchAlgorithmException e) {
LOG.warn("Error instantiating {} hash function, trying with MD5", hashFunctionName);
try {
hashAlgorithm = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException ex) {
throw new RuntimeException("Unable to instantiate MD5 digest", ex);
}
}
return hashAlgorithm;
}

/**
* Validate that the hashed payload matches data provided and stored data record
*
Expand Down