1 /*
2  * Copyright (C) 2021 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://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,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.car.telemetry.publisher;
18 
19 import android.annotation.NonNull;
20 
21 import com.android.internal.util.Preconditions;
22 
23 import java.nio.ByteBuffer;
24 import java.nio.ByteOrder;
25 import java.nio.charset.StandardCharsets;
26 import java.security.MessageDigest;
27 import java.security.NoSuchAlgorithmException;
28 
29 /**
30  * Utility class for computing hash code.
31  *
32  * <p>Most of the methods are copied from {@code external/guava/}.
33  */
34 public class HashUtils {
35     private static final long M = 0xC6A4A7935BD1E995L;
36     private static final int R = 47;
37     private static final long SEED = 0xDECAFCAFFEL;
38 
39     /**
40      * Returns the hash code of the given string using SHA-256 algorithm. Returns only the first
41      * 8 bytes if the hash code, as SHA-256 is uniformly distributed.
42      */
sha256(@onNull String data)43     public static long sha256(@NonNull String data) {
44         try {
45             return asLong(MessageDigest.getInstance("SHA-256").digest(data.getBytes()));
46         } catch (NoSuchAlgorithmException e) {
47             // unreachable
48             throw new RuntimeException("SHA-256 algorithm not found.", e);
49         }
50     }
51 
52     /**
53      * Returns the Murmur2 hash of the provided string.
54      *
55      * <p> This algorithm works the same way as Hash64() in
56      * packages/modules/StatsD/statsd/src/hash.h
57      *
58      * @param str the string to be hashed.
59      * @return hash of the string.
60      */
murmur2Hash64(String str)61     public static long murmur2Hash64(String str) {
62         final byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
63         ByteBuffer buf = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);
64 
65         long h = SEED ^ (buf.remaining() * M);
66         while (buf.remaining() >= 8) {
67             long k = buf.getLong();
68             k *= M;
69             k ^= k >>> R;
70             k *= M;
71             h ^= k;
72             h *= M;
73         }
74 
75         if (buf.hasRemaining()) {
76             for (int i = 0; buf.hasRemaining(); i += 8) {
77                 h ^= (buf.get() & 0xFFL) << i;
78             }
79             h *= M;
80         }
81 
82         h ^= h >>> R;
83         h *= M;
84         h ^= h >>> R;
85 
86         return h;
87     }
88 
89     /**
90      * Returns the first eight bytes of {@code hashCode}, converted to a {@code long} value in
91      * little-endian order.
92      *
93      * <p>Copied from Guava's {@code HashCode#asLong()}.
94      *
95      * @throws IllegalStateException if {@code hashCode bytes < 8}
96      */
asLong(byte[] hashCode)97     private static long asLong(byte[] hashCode) {
98         Preconditions.checkState(hashCode.length >= 8, "requires >= 8 bytes (it only has %s bytes)",
99                 hashCode.length);
100         long retVal = (hashCode[0] & 0xFF);
101         for (int i = 1; i < Math.min(hashCode.length, 8); i++) {
102             retVal |= (hashCode[i] & 0xFFL) << (i * 8);
103         }
104         return retVal;
105     }
106 }
107