1 /*
2  * Copyright (C) 2023 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.adservices.service.measurement.util;
18 
19 import android.annotation.NonNull;
20 import android.annotation.Nullable;
21 
22 import com.android.adservices.LoggerFactory;
23 
24 import java.security.MessageDigest;
25 import java.security.NoSuchAlgorithmException;
26 
27 public final class AdIdEncryption {
28 
29     private static final String SHA256_DIGEST_ALGORITHM_NAME = "SHA-256";
30 
AdIdEncryption()31     private AdIdEncryption() {}
32 
33     /**
34      * Encrypts adId and enrollmentId combination with SHA-256 algorithm.
35      *
36      * @param adIdValue adId to be encrypted
37      * @param enrollmentId AdTech enrollment ID to encrypt with
38      * @return encrypted adId
39      */
encryptAdIdAndEnrollmentSha256( @ullable String adIdValue, @NonNull String enrollmentId)40     public static String encryptAdIdAndEnrollmentSha256(
41             @Nullable String adIdValue, @NonNull String enrollmentId) {
42         if (adIdValue == null) {
43             LoggerFactory.getMeasurementLogger()
44                     .d("Provided adId is null; not encrypting, returning null");
45             return null;
46         }
47 
48         StringBuilder adIdSha256 = new StringBuilder();
49         String original = adIdValue + enrollmentId;
50         try {
51             // Get the hash's bytes
52             MessageDigest sha256Digest = MessageDigest.getInstance(SHA256_DIGEST_ALGORITHM_NAME);
53             byte[] encodedAdId = sha256Digest.digest(original.getBytes());
54 
55             // bytes[] has bytes in decimal format;
56             // Convert it to hexadecimal format
57             for (byte b : encodedAdId) {
58                 adIdSha256.append(String.format("%02x", b));
59             }
60         } catch (NoSuchAlgorithmException e) {
61             LoggerFactory.getMeasurementLogger()
62                     .e(e, "Unable to find correct message digest algorithm for AdId encryption.");
63             // When catching NoSuchAlgorithmException -> return null.
64             return null;
65         }
66         return adIdSha256.toString();
67     }
68 }
69