use of com.android.apksigner.core.util.DataSource in project walle by Meituan-Dianping.
the class V2SchemeSigner method generateApkSigningBlock.
/**
* Signs the provided APK using APK Signature Scheme v2 and returns the APK Signing Block
* containing the signature.
*
* @param signerConfigs signer configurations, one for each signer At least one signer config
* must be provided.
*
* @throws IOException if an I/O error occurs
* @throws InvalidKeyException if a signing key is not suitable for this signature scheme or
* cannot be used in general
* @throws SignatureException if an error occurs when computing digests of generating
* signatures
*/
public static byte[] generateApkSigningBlock(DataSource beforeCentralDir, DataSource centralDir, DataSource eocd, List<SignerConfig> signerConfigs) throws IOException, InvalidKeyException, SignatureException {
if (signerConfigs.isEmpty()) {
throw new IllegalArgumentException("No signer configs provided. At least one is required");
}
// Figure out which digest(s) to use for APK contents.
Set<ContentDigestAlgorithm> contentDigestAlgorithms = new HashSet<>(1);
for (SignerConfig signerConfig : signerConfigs) {
for (SignatureAlgorithm signatureAlgorithm : signerConfig.signatureAlgorithms) {
contentDigestAlgorithms.add(signatureAlgorithm.getContentDigestAlgorithm());
}
}
// Ensure that, when digesting, ZIP End of Central Directory record's Central Directory
// offset field is treated as pointing to the offset at which the APK Signing Block will
// start.
long centralDirOffsetForDigesting = beforeCentralDir.size();
ByteBuffer eocdBuf = ByteBuffer.allocate((int) eocd.size());
eocdBuf.order(ByteOrder.LITTLE_ENDIAN);
eocd.copyTo(0, (int) eocd.size(), eocdBuf);
eocdBuf.flip();
ZipUtils.setZipEocdCentralDirectoryOffset(eocdBuf, centralDirOffsetForDigesting);
// Compute digests of APK contents.
// digest algorithm ID -> digest
Map<ContentDigestAlgorithm, byte[]> contentDigests;
try {
contentDigests = computeContentDigests(contentDigestAlgorithms, new DataSource[] { beforeCentralDir, centralDir, DataSources.asDataSource(eocdBuf) });
} catch (IOException e) {
throw new IOException("Failed to read APK being signed", e);
} catch (DigestException e) {
throw new SignatureException("Failed to compute digests of APK", e);
}
// Sign the digests and wrap the signatures and signer info into an APK Signing Block.
return generateApkSigningBlock(signerConfigs, contentDigests);
}
use of com.android.apksigner.core.util.DataSource in project walle by Meituan-Dianping.
the class V2SchemeVerifier method verify.
/**
* Verifies the provided APK's APK Signature Scheme v2 signatures and returns the result of
* verification. APK is considered verified only if {@link Result#verified} is {@code true}. If
* verification fails, the result will contain errors -- see {@link Result#getErrors()}.
*
* @throws SignatureNotFoundException if no APK Signature Scheme v2 signatures are found
* @throws IOException if an I/O error occurs when reading the APK
*/
public static Result verify(DataSource apk, ApkUtils.ZipSections zipSections) throws IOException, SignatureNotFoundException {
Result result = new Result();
SignatureInfo signatureInfo = findSignature(apk, zipSections, result);
DataSource beforeApkSigningBlock = apk.slice(0, signatureInfo.apkSigningBlockOffset);
DataSource centralDir = apk.slice(signatureInfo.centralDirOffset, signatureInfo.eocdOffset - signatureInfo.centralDirOffset);
ByteBuffer eocd = signatureInfo.eocd;
verify(beforeApkSigningBlock, signatureInfo.signatureBlock, centralDir, eocd, result);
return result;
}
use of com.android.apksigner.core.util.DataSource in project walle by Meituan-Dianping.
the class V2SchemeSigner method computeContentDigests.
static Map<ContentDigestAlgorithm, byte[]> computeContentDigests(Set<ContentDigestAlgorithm> digestAlgorithms, DataSource[] contents) throws IOException, DigestException {
// For each digest algorithm the result is computed as follows:
// 1. Each segment of contents is split into consecutive chunks of 1 MB in size.
// The final chunk will be shorter iff the length of segment is not a multiple of 1 MB.
// No chunks are produced for empty (zero length) segments.
// 2. The digest of each chunk is computed over the concatenation of byte 0xa5, the chunk's
// length in bytes (uint32 little-endian) and the chunk's contents.
// 3. The output digest is computed over the concatenation of the byte 0x5a, the number of
// chunks (uint32 little-endian) and the concatenation of digests of chunks of all
// segments in-order.
long chunkCountLong = 0;
for (DataSource input : contents) {
chunkCountLong += getChunkCount(input.size(), CONTENT_DIGESTED_CHUNK_MAX_SIZE_BYTES);
}
if (chunkCountLong > Integer.MAX_VALUE) {
throw new DigestException("Input too long: " + chunkCountLong + " chunks");
}
int chunkCount = (int) chunkCountLong;
ContentDigestAlgorithm[] digestAlgorithmsArray = digestAlgorithms.toArray(new ContentDigestAlgorithm[digestAlgorithms.size()]);
MessageDigest[] mds = new MessageDigest[digestAlgorithmsArray.length];
byte[][] digestsOfChunks = new byte[digestAlgorithmsArray.length][];
int[] digestOutputSizes = new int[digestAlgorithmsArray.length];
for (int i = 0; i < digestAlgorithmsArray.length; i++) {
ContentDigestAlgorithm digestAlgorithm = digestAlgorithmsArray[i];
int digestOutputSizeBytes = digestAlgorithm.getChunkDigestOutputSizeBytes();
digestOutputSizes[i] = digestOutputSizeBytes;
byte[] concatenationOfChunkCountAndChunkDigests = new byte[5 + chunkCount * digestOutputSizeBytes];
concatenationOfChunkCountAndChunkDigests[0] = 0x5a;
setUnsignedInt32LittleEndian(chunkCount, concatenationOfChunkCountAndChunkDigests, 1);
digestsOfChunks[i] = concatenationOfChunkCountAndChunkDigests;
String jcaAlgorithm = digestAlgorithm.getJcaMessageDigestAlgorithm();
try {
mds[i] = MessageDigest.getInstance(jcaAlgorithm);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(jcaAlgorithm + " MessageDigest not supported", e);
}
}
MessageDigestSink mdSink = new MessageDigestSink(mds);
byte[] chunkContentPrefix = new byte[5];
chunkContentPrefix[0] = (byte) 0xa5;
int chunkIndex = 0;
// digest to be more efficient because it's presented with all of its input in one go.
for (DataSource input : contents) {
long inputOffset = 0;
long inputRemaining = input.size();
while (inputRemaining > 0) {
int chunkSize = (int) Math.min(inputRemaining, CONTENT_DIGESTED_CHUNK_MAX_SIZE_BYTES);
setUnsignedInt32LittleEndian(chunkSize, chunkContentPrefix, 1);
for (int i = 0; i < mds.length; i++) {
mds[i].update(chunkContentPrefix);
}
try {
input.feed(inputOffset, chunkSize, mdSink);
} catch (IOException e) {
throw new IOException("Failed to read chunk #" + chunkIndex, e);
}
for (int i = 0; i < digestAlgorithmsArray.length; i++) {
MessageDigest md = mds[i];
byte[] concatenationOfChunkCountAndChunkDigests = digestsOfChunks[i];
int expectedDigestSizeBytes = digestOutputSizes[i];
int actualDigestSizeBytes = md.digest(concatenationOfChunkCountAndChunkDigests, 5 + chunkIndex * expectedDigestSizeBytes, expectedDigestSizeBytes);
if (actualDigestSizeBytes != expectedDigestSizeBytes) {
throw new RuntimeException("Unexpected output size of " + md.getAlgorithm() + " digest: " + actualDigestSizeBytes);
}
}
inputOffset += chunkSize;
inputRemaining -= chunkSize;
chunkIndex++;
}
}
Map<ContentDigestAlgorithm, byte[]> result = new HashMap<>(digestAlgorithmsArray.length);
for (int i = 0; i < digestAlgorithmsArray.length; i++) {
ContentDigestAlgorithm digestAlgorithm = digestAlgorithmsArray[i];
byte[] concatenationOfChunkCountAndChunkDigests = digestsOfChunks[i];
MessageDigest md = mds[i];
byte[] digest = md.digest(concatenationOfChunkCountAndChunkDigests);
result.put(digestAlgorithm, digest);
}
return result;
}
use of com.android.apksigner.core.util.DataSource in project walle by Meituan-Dianping.
the class V2SchemeVerifier method verifyIntegrity.
/**
* Verifies integrity of the APK outside of the APK Signing Block by computing digests of the
* APK and comparing them against the digests listed in APK Signing Block. The expected digests
* taken from {@code v2SchemeSignerInfos} of the provided {@code result}.
*/
private static void verifyIntegrity(DataSource beforeApkSigningBlock, DataSource centralDir, ByteBuffer eocd, Set<ContentDigestAlgorithm> contentDigestAlgorithms, Result result) throws IOException {
if (contentDigestAlgorithms.isEmpty()) {
// is verified, meaning at least one content digest is known.
throw new RuntimeException("No content digests found");
}
// For the purposes of verifying integrity, ZIP End of Central Directory (EoCD) must be
// treated as though its Central Directory offset points to the start of APK Signing Block.
// We thus modify the EoCD accordingly.
ByteBuffer modifiedEocd = ByteBuffer.allocate(eocd.remaining());
modifiedEocd.order(ByteOrder.LITTLE_ENDIAN);
modifiedEocd.put(eocd);
modifiedEocd.flip();
ZipUtils.setZipEocdCentralDirectoryOffset(modifiedEocd, beforeApkSigningBlock.size());
Map<ContentDigestAlgorithm, byte[]> actualContentDigests;
try {
actualContentDigests = V2SchemeSigner.computeContentDigests(contentDigestAlgorithms, new DataSource[] { beforeApkSigningBlock, centralDir, new ByteBufferDataSource(modifiedEocd) });
} catch (DigestException e) {
throw new RuntimeException("Failed to compute content digests", e);
}
if (!contentDigestAlgorithms.equals(actualContentDigests.keySet())) {
throw new RuntimeException("Mismatch between sets of requested and computed content digests" + " . Requested: " + contentDigestAlgorithms + ", computed: " + actualContentDigests.keySet());
}
// in signer blocks.
for (Result.SignerInfo signerInfo : result.signers) {
for (Result.SignerInfo.ContentDigest expected : signerInfo.contentDigests) {
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.findById(expected.getSignatureAlgorithmId());
if (signatureAlgorithm == null) {
continue;
}
ContentDigestAlgorithm contentDigestAlgorithm = signatureAlgorithm.getContentDigestAlgorithm();
byte[] expectedDigest = expected.getValue();
byte[] actualDigest = actualContentDigests.get(contentDigestAlgorithm);
if (!Arrays.equals(expectedDigest, actualDigest)) {
signerInfo.addError(Issue.V2_SIG_APK_DIGEST_DID_NOT_VERIFY, contentDigestAlgorithm, toHex(expectedDigest), toHex(actualDigest));
continue;
}
signerInfo.verifiedContentDigests.put(contentDigestAlgorithm, actualDigest);
}
}
}
Aggregations