blob: 9012479c65c0616cb3fd1cd3e02fc69fd9f40fcd [file] [log] [blame]
Alice Wang0cafa142022-09-23 15:17:02 +00001/*
2 * Copyright (C) 2022 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//! API for APK Signature Scheme [v4].
18//!
19//! [v4]: https://source.android.com/security/apksigning/v4
20
Alice Wangf27626a2022-09-27 12:36:22 +000021use anyhow::{ensure, Context, Result};
Alice Wang0cafa142022-09-23 15:17:02 +000022use std::io::{Read, Seek};
23
24use crate::algorithms::SignatureAlgorithmID;
25use crate::v3::extract_signer_and_apk_sections;
26
27/// Gets the v4 [apk_digest]. If `verify` is true, we verify that digest computed
28/// with the extracted algorithm is equal to the digest extracted directly from apk.
29/// Otherwise, the extracted digest will be returned directly.
30///
31/// [apk_digest]: https://source.android.com/docs/security/apksigning/v4#apk-digest
32pub fn get_apk_digest<R: Read + Seek>(
33 apk: R,
34 verify: bool,
35) -> Result<(SignatureAlgorithmID, Box<[u8]>)> {
36 let (signer, mut sections) = extract_signer_and_apk_sections(apk)?;
Alice Wangf27626a2022-09-27 12:36:22 +000037 let strongest_algorithm_id = signer
38 .strongest_signature()?
39 .signature_algorithm_id
40 .context("Strongest signature should contain a valid signature algorithm.")?;
41 let extracted_digest = signer.find_digest_by_algorithm(strongest_algorithm_id)?;
Alice Wang0cafa142022-09-23 15:17:02 +000042 if verify {
Alice Wangf27626a2022-09-27 12:36:22 +000043 let computed_digest = sections.compute_digest(strongest_algorithm_id)?;
Alice Wang0cafa142022-09-23 15:17:02 +000044 ensure!(
45 computed_digest == extracted_digest.as_ref(),
46 "Computed digest does not match the extracted digest."
47 );
48 }
Alice Wangf27626a2022-09-27 12:36:22 +000049 Ok((strongest_algorithm_id, extracted_digest))
Alice Wang0cafa142022-09-23 15:17:02 +000050}