Class SecureObjectIdentityHash

java.lang.Object
io.netty.util.SecureObjectIdentityHash

public final class SecureObjectIdentityHash extends Object
A secure way to associate 256 bits of entropy with the identity of an object. This is the 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 Details

    • SecureObjectIdentityHash

      public SecureObjectIdentityHash()
      Create a new instance.
    • SecureObjectIdentityHash

      public SecureObjectIdentityHash(SecureRandom random)
      Create a new instance, initialized with the given SecureRandom instance.

      Note: Prefer the no-arg SecureObjectIdentityHash() constructor. Only use this method if you have very specific requirements of your secure random generators.

      Parameters:
      random - The SecureRandom instance to use, not null.
  • Method Details

    • getHashLengthBytes

      public int getHashLengthBytes()
      Get the length of the hash values, in bytes.
      Returns:
      The hash value length in bytes.
    • getIdentityHash

      public byte @NotNull [] getIdentityHash(@Nullable @Nullable Object obj)
      Get the secure object identity hash for the given object.

      It is possible to get an identity hash value for null, but beware that all null values 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 be null.
      Returns:
      The identity hash value.
    • updateWithIdentityHash

      public void updateWithIdentityHash(MessageDigest digest, @Nullable @Nullable Object obj)
      Update the given MessageDigest with the hash value for the given object.

      It is possible to get an identity hash value for null, but beware that all null values 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 - The MessageDigest to update with the hash of the given object. The digest receives a single MessageDigest.update(byte[]) call, with no length prefix or suffix.
      obj - The object to get the identity hash for. Can be null.