+def ReadApkCerts(tf_zip):
+ """Given a target_files ZipFile, parse the META/apkcerts.txt file
+ and return a {package: cert} dict."""
+ certmap = {}
+ for line in tf_zip.read("META/apkcerts.txt").split("\n"):
+ line = line.strip()
+ if not line: continue
+ m = re.match(r'^name="(.*)"\s+certificate="(.*)"\s+'
+ r'private_key="(.*)"$', line)
+ if m:
+ name, cert, privkey = m.groups()
+ if cert in SPECIAL_CERT_STRINGS and not privkey:
+ certmap[name] = cert
+ elif (cert.endswith(".x509.pem") and
+ privkey.endswith(".pk8") and
+ cert[:-9] == privkey[:-4]):
+ certmap[name] = cert[:-9]
+ else:
+ raise ValueError("failed to parse line from apkcerts.txt:\n" + line)
+ return certmap
+
+