Skip to content

Commit e3a36c9

Browse files
authored
Fixed thread-safety issue of MessageDigest (#817)
1 parent 52a1d03 commit e3a36c9

File tree

1 file changed

+19
-12
lines changed

1 file changed

+19
-12
lines changed

powertools-idempotency/src/main/java/software/amazon/lambda/powertools/idempotency/persistence/BasePersistenceStore.java

+19-12
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ public abstract class BasePersistenceStore implements PersistenceStore {
6060
protected boolean payloadValidationEnabled = false;
6161
private Expression<JsonNode> validationKeyJMESPath;
6262
private boolean throwOnNoIdempotencyKey = false;
63-
private MessageDigest hashAlgorithm;
63+
private String hashFunctionName;
6464

6565
/**
6666
* Initialize the base persistence layer from the configuration settings
@@ -95,17 +95,7 @@ public void configure(IdempotencyConfig config, String functionName) {
9595
cache = new LRUCache<>(config.getLocalCacheMaxItems());
9696
}
9797
expirationInSeconds = config.getExpirationInSeconds();
98-
99-
try {
100-
hashAlgorithm = MessageDigest.getInstance(config.getHashFunction());
101-
} catch (NoSuchAlgorithmException e) {
102-
LOG.warn("Error instantiating {} hash function, trying with MD5", config.getHashFunction());
103-
try {
104-
hashAlgorithm = MessageDigest.getInstance("MD5");
105-
} catch (NoSuchAlgorithmException ex) {
106-
throw new RuntimeException("Unable to instantiate MD5 digest", ex);
107-
}
108-
}
98+
hashFunctionName = config.getHashFunction();
10999
configured = true;
110100
}
111101

@@ -275,10 +265,27 @@ String generateHash(JsonNode data) {
275265
} else if (data.isBoolean()) {
276266
node = data.asBoolean();
277267
} else node = data; // anything else
268+
269+
MessageDigest hashAlgorithm = getHashAlgorithm();
278270
byte[] digest = hashAlgorithm.digest(node.toString().getBytes(StandardCharsets.UTF_8));
279271
return String.format("%032x", new BigInteger(1, digest));
280272
}
281273

274+
private MessageDigest getHashAlgorithm() {
275+
MessageDigest hashAlgorithm;
276+
try {
277+
hashAlgorithm = MessageDigest.getInstance(hashFunctionName);
278+
} catch (NoSuchAlgorithmException e) {
279+
LOG.warn("Error instantiating {} hash function, trying with MD5", hashFunctionName);
280+
try {
281+
hashAlgorithm = MessageDigest.getInstance("MD5");
282+
} catch (NoSuchAlgorithmException ex) {
283+
throw new RuntimeException("Unable to instantiate MD5 digest", ex);
284+
}
285+
}
286+
return hashAlgorithm;
287+
}
288+
282289
/**
283290
* Validate that the hashed payload matches data provided and stored data record
284291
*

0 commit comments

Comments
 (0)