View Javadoc
1   /*
2    * Copyright 2026 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.util;
17  
18  import io.netty.util.internal.WeakIdentityHashMap;
19  import org.jetbrains.annotations.NotNull;
20  import org.jetbrains.annotations.Nullable;
21  
22  import java.security.MessageDigest;
23  import java.security.SecureRandom;
24  import java.util.Arrays;
25  import java.util.Map;
26  import java.util.Objects;
27  import java.util.function.Function;
28  
29  /**
30   * A secure way to associate 256 bits of entropy with the <em>identity</em> of an object.
31   * This is the {@link SecureRandom} version, or {@code SHA-256} version, of {@link System#identityHashCode(Object)}.
32   * <p>
33   * <strong>Note:</strong> You can create <em>domain separation</em> between the identity hashes by having more than
34   * one instance of this class. Each instance will create their own distinct hashes for the same objects.
35   * <p>
36   * The way this works internally is by using a {@link WeakIdentityHashMap} that uses <em>object identity</em>
37   * (instead of {@link Object#equals(Object)} and {@link Object#hashCode()}) to associate objects with a 32-byte
38   * token.
39   * The token values are derived from a {@link SecureRandom} instance.
40   * <p>
41   * This class is thread-safe. Proper synchronization is done internally, so using {@code synchronized} on instances
42   * of this class has no effect on its operation.
43   */
44  public final class SecureObjectIdentityHash {
45      private static final int HASH_LENGTH_BYTES = 32; // 256 bits.
46      private static final Function<Object, Token> CREATE_TOKEN = ignore -> new Token();
47  
48      private final SecureRandom random;
49      private final Map<Object, Token> mapping;
50      private final Token nullToken;
51  
52      /**
53       * Create a new instance.
54       */
55      public SecureObjectIdentityHash() {
56          this(new SecureRandom());
57      }
58  
59      /**
60       * Create a new instance, initialized with the given {@link SecureRandom} instance.
61       * <p>
62       * <strong>Note:</strong> Prefer the no-arg {@link SecureObjectIdentityHash()} constructor.
63       * Only use this method if you have <em>very specific requirements</em> of your secure random generators.
64       * @param random The {@link SecureRandom} instance to use, not {@code null}.
65       */
66      public SecureObjectIdentityHash(SecureRandom random) {
67          this.random = Objects.requireNonNull(random, "random");
68          mapping = new WeakIdentityHashMap<>();
69          nullToken = new Token();
70      }
71  
72      /**
73       * Get the length of the hash values, in bytes.
74       * @return The hash value length in bytes.
75       */
76      public int getHashLengthBytes() {
77          return HASH_LENGTH_BYTES;
78      }
79  
80      /**
81       * Get the secure object identity hash for the given object.
82       * <p>
83       * It is possible to get an identity hash value for {@code null}, but beware that all {@code null} values get
84       * the same identity hash value.
85       * <p>
86       * The returned byte array is a copy of the internal value, so modifying it does not influence subsequent
87       * or concurrent calls.
88       * @param obj The object to get the identity hash for. Can be {@code null}.
89       * @return The identity hash value.
90       */
91      public byte @NotNull [] getIdentityHash(@Nullable Object obj) {
92          Token token = getTokenFor(obj);
93          return token.getValueCopy(random);
94      }
95  
96      /**
97       * Update the given {@link MessageDigest} with the hash value for the given object.
98       * <p>
99       * It is possible to get an identity hash value for {@code null}, but beware that all {@code null} values get
100      * the same identity hash value.
101      * <p>
102      * The returned byte array is a copy of the internal value, so modifying it does not influence subsequent
103      * or concurrent calls.
104      * @param digest The {@link MessageDigest} to update with the hash of the given object.
105      *              The digest receives a single {@link MessageDigest#update(byte[])} call,
106      *              with no length prefix or suffix.
107      * @param obj The object to get the identity hash for. Can be {@code null}.
108      */
109     public void updateWithIdentityHash(MessageDigest digest, @Nullable Object obj) {
110         Token token = getTokenFor(obj);
111         token.updateDigest(random, digest);
112     }
113 
114     private Token getTokenFor(Object obj) {
115         if (obj == null) {
116             return nullToken;
117         }
118         synchronized (mapping) {
119             return mapping.computeIfAbsent(obj, CREATE_TOKEN);
120         }
121     }
122 
123     private static final class Token {
124         private volatile byte[] value;
125         private int checksum;
126 
127         public byte[] getValueCopy(SecureRandom random) {
128             byte[] value = getOrCreateTokenValue(random);
129             return value.clone();
130         }
131 
132         @SuppressWarnings({"AssertWithSideEffects", "ConstantValue"})
133         public void updateDigest(SecureRandom random, MessageDigest digest) {
134             byte[] value = getOrCreateTokenValue(random);
135             digest.update(value);
136             // Best-effort at detecting nefarious 'MessageDigest' implementations; blow away stored hash if detected.
137             assert checksum == Arrays.hashCode(value) || (this.value = null) != null :
138                 "MessageDigest " + digest + " modified its input array! " +
139                     "Switch to an implementation that does not do this";
140         }
141 
142         private byte @NotNull [] getOrCreateTokenValue(SecureRandom random) {
143             byte[] value = this.value;
144             if (value == null) {
145                 synchronized (this) {
146                     value = this.value;
147                     if (value == null) {
148                         value = new byte[HASH_LENGTH_BYTES];
149                         random.nextBytes(value);
150                         checksum = Arrays.hashCode(value);
151                         this.value = value;
152                     }
153                 }
154             }
155             return value;
156         }
157     }
158 }