This rule raises an issue when a MessageDigest object is declared as a class-level variable (either instance-level or shared across
all instances).
Cryptographic hash computation objects are stateful components that calculate hash values by maintaining internal state as data is incrementally processed through their methods.
The problem is that these hash computation objects are not thread-safe. When stored as shared state (such as class-level fields or instance variables), the same object becomes accessible to multiple threads or multiple method invocations. If two threads invoke methods on the same hash computation object simultaneously, or if the object is reused between method calls without proper synchronization, the internal state becomes corrupted.
This corruption leads to incorrect hash calculations. The resulting hash values may be completely wrong or inconsistent, which defeats the purpose of using cryptographic hashing in the first place.
While it’s technically possible to synchronize access to a shared hash computation object, this approach adds complexity and potential performance bottlenecks. The synchronization overhead often negates any perceived performance benefits of reusing the object.
Creating a new hash computation object for each use is relatively inexpensive. Modern runtime environments optimize object allocation efficiently, and the cost of instantiation is negligible compared to the actual hash computation work.
In Java, this specifically refers to the MessageDigest class from the Java Security API, which provides methods like
update() and digest() for hash computation.
When hash calculations produce incorrect results due to unsynchronized access to shared hash computation objects or functions, the consequences can be severe:
These issues are particularly insidious because they may occur intermittently based on timing, making them difficult to detect during testing but capable of causing production failures.
Create the MessageDigest instance locally within the method that needs it, rather than storing it as a field. This ensures each
operation has its own instance with isolated state.
import java.security.MessageDigest;
public class HashCalculator {
private final MessageDigest digest; // Noncompliant
public HashCalculator() throws Exception {
digest = MessageDigest.getInstance("SHA-256");
}
public byte[] computeHash(byte[] data) {
digest.reset();
digest.update(data);
return digest.digest();
}
}
import java.security.MessageDigest;
public class HashCalculator {
public byte[] computeHash(byte[] data) throws Exception {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.update(data);
return digest.digest();
}
}