1 /* 2 * Copyright (C) 2016 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 android.util; 18 19 import android.annotation.NonNull; 20 import android.annotation.Nullable; 21 import android.content.pm.PackageInfo; 22 import android.content.pm.PackageManager; 23 import android.content.pm.Signature; 24 25 import java.security.MessageDigest; 26 import java.security.NoSuchAlgorithmException; 27 28 /** 29 * Helper functions applicable to packages. 30 * @hide 31 */ 32 public final class PackageUtils { 33 PackageUtils()34 private PackageUtils() { 35 /* hide constructor */ 36 } 37 38 /** 39 * Computes the SHA256 digest of the signing cert for a package. 40 * @param packageManager The package manager. 41 * @param packageName The package for which to generate the digest. 42 * @param userId The user for which to generate the digest. 43 * @return The digest or null if the package does not exist for this user. 44 */ computePackageCertSha256Digest( @onNull PackageManager packageManager, @NonNull String packageName, int userId)45 public static @Nullable String computePackageCertSha256Digest( 46 @NonNull PackageManager packageManager, 47 @NonNull String packageName, int userId) { 48 final PackageInfo packageInfo; 49 try { 50 packageInfo = packageManager.getPackageInfoAsUser(packageName, 51 PackageManager.GET_SIGNATURES, userId); 52 } catch (PackageManager.NameNotFoundException e) { 53 return null; 54 } 55 return computeCertSha256Digest(packageInfo.signatures[0]); 56 } 57 58 /** 59 * Computes the SHA256 digest of a cert. 60 * @param signature The signature. 61 * @return The digest or null if an error occurs. 62 */ computeCertSha256Digest(@onNull Signature signature)63 public static @Nullable String computeCertSha256Digest(@NonNull Signature signature) { 64 return computeSha256Digest(signature.toByteArray()); 65 } 66 67 /** 68 * Computes the SHA256 digest of some data. 69 * @param data The data. 70 * @return The digest or null if an error occurs. 71 */ computeSha256Digest(@onNull byte[] data)72 public static @Nullable String computeSha256Digest(@NonNull byte[] data) { 73 MessageDigest messageDigest; 74 try { 75 messageDigest = MessageDigest.getInstance("SHA256"); 76 } catch (NoSuchAlgorithmException e) { 77 /* can't happen */ 78 return null; 79 } 80 81 messageDigest.update(data); 82 83 return ByteStringUtils.toHexString(messageDigest.digest()); 84 } 85 } 86