blob: d0522a73ca225e324d2950a205cbea88255898d0 [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
21use anyhow::{ensure, Result};
22use 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)?;
37 let (signature_algorithm_id, extracted_digest) = signer.pick_v4_apk_digest()?;
38 if verify {
39 let computed_digest = sections.compute_digest(signature_algorithm_id)?;
40 ensure!(
41 computed_digest == extracted_digest.as_ref(),
42 "Computed digest does not match the extracted digest."
43 );
44 }
45 Ok((signature_algorithm_id, extracted_digest))
46}