|
| 1 | +package com.google.firebase.appdistribution.impl; |
| 2 | + |
| 3 | +import static com.google.firebase.appdistribution.impl.ReleaseIdentificationUtils.getPackageInfoWithMetadata; |
| 4 | + |
| 5 | +import android.content.Context; |
| 6 | +import android.content.pm.PackageInfo; |
| 7 | +import androidx.annotation.NonNull; |
| 8 | +import androidx.annotation.Nullable; |
| 9 | +import androidx.annotation.VisibleForTesting; |
| 10 | +import com.google.firebase.appdistribution.FirebaseAppDistributionException; |
| 11 | +import com.google.firebase.appdistribution.FirebaseAppDistributionException.Status; |
| 12 | +import java.io.File; |
| 13 | +import java.io.IOException; |
| 14 | +import java.nio.ByteBuffer; |
| 15 | +import java.security.MessageDigest; |
| 16 | +import java.security.NoSuchAlgorithmException; |
| 17 | +import java.util.ArrayList; |
| 18 | +import java.util.Enumeration; |
| 19 | +import java.util.Locale; |
| 20 | +import java.util.concurrent.ConcurrentHashMap; |
| 21 | +import java.util.concurrent.ConcurrentMap; |
| 22 | +import java.util.zip.ZipEntry; |
| 23 | +import java.util.zip.ZipFile; |
| 24 | + |
| 25 | +/** Extracts a hash of the installed APK. */ |
| 26 | +class ApkHashExtractor { |
| 27 | + |
| 28 | + private static final String TAG = "ApkHashExtractor:"; |
| 29 | + private static final int BYTES_IN_LONG = 8; |
| 30 | + |
| 31 | + private final ConcurrentMap<String, String> cachedApkHashes = new ConcurrentHashMap<>(); |
| 32 | + private Context applicationContext; |
| 33 | + |
| 34 | + ApkHashExtractor(Context applicationContext) { |
| 35 | + this.applicationContext = applicationContext; |
| 36 | + } |
| 37 | + |
| 38 | + /** |
| 39 | + * Extract the SHA-256 hash of the installed APK. |
| 40 | + * |
| 41 | + * <p>The result is stored in an in-memory cache to avoid computing it repeatedly. |
| 42 | + */ |
| 43 | + String extractApkHash() throws FirebaseAppDistributionException { |
| 44 | + PackageInfo metadataPackageInfo = getPackageInfoWithMetadata(applicationContext); |
| 45 | + String installedReleaseApkHash = extractApkHash(metadataPackageInfo); |
| 46 | + if (installedReleaseApkHash == null || installedReleaseApkHash.isEmpty()) { |
| 47 | + throw new FirebaseAppDistributionException( |
| 48 | + "Could not calculate hash of installed APK", Status.UNKNOWN); |
| 49 | + } |
| 50 | + return installedReleaseApkHash; |
| 51 | + } |
| 52 | + |
| 53 | + @VisibleForTesting |
| 54 | + String extractApkHash(PackageInfo packageInfo) { |
| 55 | + File sourceFile = new File(packageInfo.applicationInfo.sourceDir); |
| 56 | + |
| 57 | + String key = |
| 58 | + String.format( |
| 59 | + Locale.ENGLISH, "%s.%d", sourceFile.getAbsolutePath(), sourceFile.lastModified()); |
| 60 | + if (!cachedApkHashes.containsKey(key)) { |
| 61 | + cachedApkHashes.put(key, calculateApkHash(sourceFile)); |
| 62 | + } |
| 63 | + return cachedApkHashes.get(key); |
| 64 | + } |
| 65 | + |
| 66 | + @Nullable |
| 67 | + String calculateApkHash(@NonNull File file) { |
| 68 | + LogWrapper.getInstance().v(TAG + "Calculating release id for " + file.getPath()); |
| 69 | + LogWrapper.getInstance().v(TAG + "File size: " + file.length()); |
| 70 | + |
| 71 | + long start = System.currentTimeMillis(); |
| 72 | + long entries = 0; |
| 73 | + String zipFingerprint = null; |
| 74 | + try { |
| 75 | + MessageDigest digest = MessageDigest.getInstance("SHA-256"); |
| 76 | + ArrayList<Byte> checksums = new ArrayList<>(); |
| 77 | + |
| 78 | + // Since calculating the codeHash returned from the release backend is computationally |
| 79 | + // expensive, we has the existing checksum data from the ZipFile and compare it to |
| 80 | + // (1) the apk hash returned by the backend, or (2) look up a mapping from the apk zip hash to |
| 81 | + // the |
| 82 | + // full codehash, and compare that to the codehash to the backend |
| 83 | + ZipFile zis = new ZipFile(file); |
| 84 | + try { |
| 85 | + Enumeration<? extends ZipEntry> zipEntries = zis.entries(); |
| 86 | + while (zipEntries.hasMoreElements()) { |
| 87 | + ZipEntry zip = zipEntries.nextElement(); |
| 88 | + entries += 1; |
| 89 | + byte[] crcBytes = longToByteArray(zip.getCrc()); |
| 90 | + for (byte b : crcBytes) { |
| 91 | + checksums.add(b); |
| 92 | + } |
| 93 | + } |
| 94 | + } finally { |
| 95 | + zis.close(); |
| 96 | + } |
| 97 | + byte[] checksumByteArray = digest.digest(arrayListToByteArray(checksums)); |
| 98 | + StringBuilder sb = new StringBuilder(); |
| 99 | + for (byte b : checksumByteArray) { |
| 100 | + sb.append(String.format("%02x", b)); |
| 101 | + } |
| 102 | + zipFingerprint = sb.toString(); |
| 103 | + |
| 104 | + } catch (IOException | NoSuchAlgorithmException e) { |
| 105 | + LogWrapper.getInstance().v(TAG + "id calculation failed for " + file.getPath()); |
| 106 | + return null; |
| 107 | + } finally { |
| 108 | + long elapsed = System.currentTimeMillis() - start; |
| 109 | + if (elapsed > 2 * 1000) { |
| 110 | + LogWrapper.getInstance() |
| 111 | + .v( |
| 112 | + TAG |
| 113 | + + String.format( |
| 114 | + "Long id calculation time %d ms and %d entries for %s", |
| 115 | + elapsed, entries, file.getPath())); |
| 116 | + } |
| 117 | + |
| 118 | + LogWrapper.getInstance() |
| 119 | + .v(TAG + String.format("Finished calculating %d entries in %d ms", entries, elapsed)); |
| 120 | + LogWrapper.getInstance() |
| 121 | + .v(TAG + String.format("%s hashes to %s", file.getPath(), zipFingerprint)); |
| 122 | + } |
| 123 | + |
| 124 | + return zipFingerprint; |
| 125 | + } |
| 126 | + |
| 127 | + private static byte[] longToByteArray(long x) { |
| 128 | + ByteBuffer buffer = ByteBuffer.allocate(BYTES_IN_LONG); |
| 129 | + buffer.putLong(x); |
| 130 | + return buffer.array(); |
| 131 | + } |
| 132 | + |
| 133 | + private static byte[] arrayListToByteArray(ArrayList<Byte> list) { |
| 134 | + byte[] result = new byte[list.size()]; |
| 135 | + for (int i = 0; i < list.size(); i++) { |
| 136 | + result[i] = list.get(i); |
| 137 | + } |
| 138 | + return result; |
| 139 | + } |
| 140 | +} |
0 commit comments