Class SecureObjectIdentityHash
SecureRandom version, or SHA-256 version, of System.identityHashCode(Object).
Note: You can create domain separation between the identity hashes by having more than one instance of this class. Each instance will create their own distinct hashes for the same objects.
The way this works internally is by using a WeakIdentityHashMap that uses object identity
(instead of Object.equals(Object) and Object.hashCode()) to associate objects with a 32-byte
token.
The token values are derived from a SecureRandom instance.
This class is thread-safe. Proper synchronization is done internally, so using synchronized on instances
of this class has no effect on its operation.
-
Constructor Summary
ConstructorsConstructorDescriptionCreate a new instance.SecureObjectIdentityHash(SecureRandom random) Create a new instance, initialized with the givenSecureRandominstance. -
Method Summary
Modifier and TypeMethodDescriptionintGet the length of the hash values, in bytes.byte @NotNull []getIdentityHash(@Nullable Object obj) Get the secure object identity hash for the given object.voidupdateWithIdentityHash(MessageDigest digest, @Nullable Object obj) Update the givenMessageDigestwith the hash value for the given object.
-
Constructor Details
-
SecureObjectIdentityHash
public SecureObjectIdentityHash()Create a new instance. -
SecureObjectIdentityHash
Create a new instance, initialized with the givenSecureRandominstance.Note: Prefer the no-arg
SecureObjectIdentityHash()constructor. Only use this method if you have very specific requirements of your secure random generators.- Parameters:
random- TheSecureRandominstance to use, notnull.
-
-
Method Details
-
getHashLengthBytes
public int getHashLengthBytes()Get the length of the hash values, in bytes.- Returns:
- The hash value length in bytes.
-
getIdentityHash
Get the secure object identity hash for the given object.It is possible to get an identity hash value for
null, but beware that allnullvalues get the same identity hash value.The returned byte array is a copy of the internal value, so modifying it does not influence subsequent or concurrent calls.
- Parameters:
obj- The object to get the identity hash for. Can benull.- Returns:
- The identity hash value.
-
updateWithIdentityHash
Update the givenMessageDigestwith the hash value for the given object.It is possible to get an identity hash value for
null, but beware that allnullvalues get the same identity hash value.The returned byte array is a copy of the internal value, so modifying it does not influence subsequent or concurrent calls.
- Parameters:
digest- TheMessageDigestto update with the hash of the given object. The digest receives a singleMessageDigest.update(byte[])call, with no length prefix or suffix.obj- The object to get the identity hash for. Can benull.
-