Skip to content

Commit 44cc219

Browse files
runningcodeclaude
andcommitted
feat(android-distribution): Add APK binary identifier extraction
This PR adds APK signing digest extraction functionality for unique build identification, similar to Emerge Tools' approach. ### Changes - Add `BinaryIdentifier.kt` with complete APK parsing implementation - Extract SHA-256/SHA-512 digests from APK signing blocks (V2/V3 signatures) - Update `DistributionInternal.kt` to use binary identifier extraction - Follow Android APK signing format specification ### Implementation Details - Reads APK file directly using RandomAccessFile - Parses ZIP structure to locate APK Signing Block - Extracts first available digest from V2 or V3 signature schemes - Returns Base64-encoded digest as stable build identifier - Gracefully handles failures (returns null if extraction fails) - Zero external dependencies (uses Android's built-in Base64) 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
1 parent b60f232 commit 44cc219

File tree

2 files changed

+150
-2
lines changed

2 files changed

+150
-2
lines changed
Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
@file:Suppress("MagicNumber", "NestedBlockDepth", "TooManyFunctions")
2+
3+
package io.sentry.android.distribution.internal
4+
5+
import android.content.Context
6+
import android.util.Base64
7+
import java.io.RandomAccessFile
8+
import java.nio.charset.StandardCharsets
9+
10+
private const val EOCD_MINIMUM_SIZE = 22
11+
private const val EOCD_MAGIC_LE = 0x06054b50
12+
private val EOCD_MAGIC_BE = Integer.reverseBytes(EOCD_MAGIC_LE)
13+
14+
private const val SIGNING_BLOCK_MAGIC = "APK Sig Block 42"
15+
private const val SIGNING_BLOCK_SUFFIX_SIZE = 16 + 8
16+
17+
private const val V2_BLOCK_ID = 0x7109871aL
18+
private const val V3_BLOCK_ID = 0xf05368c0L
19+
20+
private fun readLittleEndianU32(fd: RandomAccessFile): Long {
21+
var u32 = 0L
22+
u32 = u32 or (fd.readByte().toLong() and 0xFFL).shl(8 * 0)
23+
u32 = u32 or (fd.readByte().toLong() and 0xFFL).shl(8 * 1)
24+
u32 = u32 or (fd.readByte().toLong() and 0xFFL).shl(8 * 2)
25+
u32 = u32 or (fd.readByte().toLong() and 0xFFL).shl(8 * 3)
26+
return u32
27+
}
28+
29+
private fun readLittleEndianU64(fd: RandomAccessFile): Long {
30+
var u64 = 0L
31+
u64 = u64 or (fd.readByte().toLong() and 0xFFL).shl(8 * 0)
32+
u64 = u64 or (fd.readByte().toLong() and 0xFFL).shl(8 * 1)
33+
u64 = u64 or (fd.readByte().toLong() and 0xFFL).shl(8 * 2)
34+
u64 = u64 or (fd.readByte().toLong() and 0xFFL).shl(8 * 3)
35+
u64 = u64 or (fd.readByte().toLong() and 0xFFL).shl(8 * 4)
36+
u64 = u64 or (fd.readByte().toLong() and 0xFFL).shl(8 * 5)
37+
u64 = u64 or (fd.readByte().toLong() and 0xFFL).shl(8 * 6)
38+
u64 = u64 or (fd.readByte().toLong() and 0xFFL).shl(8 * 7)
39+
return u64
40+
}
41+
42+
private fun getBinaryIdentifierFromApk(fd: RandomAccessFile): String? {
43+
val end = fd.length()
44+
45+
// We make some assumptions below to minimize complexity since setting
46+
// binaryIdentifier is not critical. The first such assumption is assuming
47+
// no zip comment:
48+
val startOfEocd = end - EOCD_MINIMUM_SIZE
49+
50+
// Find the start of the central directory:
51+
fd.seek(startOfEocd)
52+
val eocdMagic = fd.readInt()
53+
if (eocdMagic != EOCD_MAGIC_BE) {
54+
return null
55+
}
56+
fd.skipBytes(12)
57+
val cdOffset = readLittleEndianU32(fd)
58+
59+
// Find (and seek to) the start of the signing block:
60+
fd.seek(cdOffset - SIGNING_BLOCK_SUFFIX_SIZE)
61+
val signingBlockSize = readLittleEndianU64(fd)
62+
val signingBlockMagic = ByteArray(16)
63+
fd.read(signingBlockMagic)
64+
if (String(signingBlockMagic, StandardCharsets.UTF_8) != SIGNING_BLOCK_MAGIC) {
65+
return null
66+
}
67+
fd.seek(cdOffset - signingBlockSize)
68+
69+
val endOfPairs = fd.filePointer + signingBlockSize - SIGNING_BLOCK_SUFFIX_SIZE
70+
71+
while (fd.filePointer < endOfPairs) {
72+
val id = readLittleEndianU32(fd)
73+
val size = readLittleEndianU32(fd)
74+
val endOfBlock = fd.filePointer + size
75+
// The structure of V2, V3, V3.1 is the same as far as getting the digests
76+
// which is all we need to do:
77+
if (id == V2_BLOCK_ID || id == V3_BLOCK_ID) {
78+
while (fd.filePointer < endOfBlock) {
79+
val signerSize = readLittleEndianU32(fd)
80+
val signerEnd = signerSize + fd.filePointer
81+
82+
val signedDataSize = readLittleEndianU32(fd)
83+
val signedDataEnd = signedDataSize + fd.filePointer
84+
85+
val digestsSize = readLittleEndianU32(fd)
86+
val digestsEnd = digestsSize + fd.filePointer
87+
88+
while (fd.filePointer < digestsEnd) {
89+
val digestSize = readLittleEndianU32(fd)
90+
val digestEnd = digestSize + fd.filePointer
91+
92+
// signatureAlgorithmId
93+
readLittleEndianU32(fd)
94+
val digestLength = readLittleEndianU32(fd)
95+
if (digestLength == 32L || digestLength == 64L) {
96+
val digest = ByteArray(digestLength.toInt())
97+
fd.read(digest)
98+
return Base64.encodeToString(digest, Base64.NO_WRAP)
99+
}
100+
101+
fd.seek(digestEnd)
102+
}
103+
104+
fd.seek(digestsEnd)
105+
fd.seek(signedDataEnd)
106+
fd.seek(signerEnd)
107+
}
108+
}
109+
fd.seek(endOfBlock)
110+
}
111+
112+
return null
113+
}
114+
115+
/**
116+
* Get a stable identifier which uniquely identifies a given build of an APK.
117+
*
118+
* We attempt to extract the first available digest computed for APK signing from the APK's signing
119+
* block. This provides a unique identifier for each build that doesn't rely on versionName or
120+
* versionCode which are often not updated between builds.
121+
*
122+
* The implementation reads the APK file directly to extract signing digests following the Android
123+
* APK signing format. See https://source.android.com/docs/security/features/apksigning
124+
*
125+
* @param context Android context to get the application info
126+
* @return Base64-encoded digest string if found, null otherwise
127+
*/
128+
internal fun getBinaryIdentifier(context: Context): String? {
129+
return try {
130+
val info = context.packageManager.getApplicationInfo(context.packageName, 0)
131+
val path = info.sourceDir
132+
RandomAccessFile(path, "r").use { fd -> getBinaryIdentifierFromApk(fd) }
133+
} catch (e: Exception) {
134+
// If we can't read the APK for any reason, return null
135+
// This is not critical for the distribution functionality
136+
null
137+
}
138+
}

sentry-android-distribution/src/main/java/io/sentry/android/distribution/internal/DistributionInternal.kt

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,22 @@ internal object DistributionInternal {
2020
}
2121

2222
fun checkForUpdate(context: Context): UpdateStatus {
23-
return UpdateStatus.Error("Implementation coming in future PR")
23+
// Test binary identifier extraction works
24+
val binaryIdentifier = getBinaryIdentifier(context)
25+
return if (binaryIdentifier != null) {
26+
UpdateStatus.Error(
27+
"Binary identifier extracted: $binaryIdentifier. HTTP client and API models coming in future PRs."
28+
)
29+
} else {
30+
UpdateStatus.Error(
31+
"Could not extract binary identifier. HTTP client and API models coming in future PRs."
32+
)
33+
}
2434
}
2535

2636
fun checkForUpdateCompletableFuture(context: Context): CompletableFuture<UpdateStatus> {
2737
val future = CompletableFuture<UpdateStatus>()
28-
future.complete(UpdateStatus.Error("Implementation coming in future PR"))
38+
future.complete(checkForUpdate(context))
2939
return future
3040
}
3141
}

0 commit comments

Comments
 (0)