• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2024 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 package android.app.appsearch.testutil;
17 
18 import android.content.Context;
19 import android.content.pm.PackageInfo;
20 import android.content.pm.PackageManager;
21 import android.content.pm.SigningInfo;
22 
23 import java.security.MessageDigest;
24 
25 /**
26  * Class to hold utilities for accessing packages.
27  */
28 public class PackageUtil {
29 
PackageUtil()30     private PackageUtil() {}
31 
32     /**
33      * Returns the SHA-256 signing certificate of this CTS package.
34      *
35      * <p>CTS apps are not always signed with the same key, and so we need to obtain it in runtime.
36      */
getSelfPackageSha256Cert(Context context)37     public static byte[] getSelfPackageSha256Cert(Context context) throws Exception {
38         PackageInfo packageInfo = context.getPackageManager().getPackageInfo(
39                 context.getPackageName(), PackageManager.GET_SIGNING_CERTIFICATES);
40         SigningInfo signingInfo = packageInfo.signingInfo;
41         if (signingInfo == null || signingInfo.getSigningCertificateHistory() == null) {
42             throw new IllegalStateException("Failed to get the signing certificate");
43         }
44         MessageDigest md = MessageDigest.getInstance("SHA256");
45         md.update(signingInfo.getSigningCertificateHistory()[0].toByteArray());
46         return md.digest();
47     }
48 }
49