When you designate a MessageDigest instance as a class member, you enable direct access for multiple threads in your program. It is important to exercise caution when sharing instances among threads without proper synchronization.
Instead of sharing a single MessageDigest instance, consider generating new instances when necessary and using them locally within the specific context where they are needed. This practice offers two benefits. First, it guarantees that each thread operates on its own instance, thereby minimizing the possibility of interference between threads. Second, it sidesteps the intricacies of managing synchronized access to a shared instance.
Non-Compliant Code Examples
publicclassFoo{privatefinalMessageDigestsharedMd;// should avoid thispublicFoo()throwsException{sharedMd=MessageDigest.getInstance("SHA-256");}publicbyte[]bar(byte[]data){// Incorrect outcomes could arise from sharing a // MessageDigest without synchronized access.sharedMd.reset();sharedMd.update(data);returnsharedMd.digest();}}