Alice Wang | 0cafa14 | 2022-09-23 15:17:02 +0000 | [diff] [blame] | 1 | /* |
| 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 Wang | f27626a | 2022-09-27 12:36:22 +0000 | [diff] [blame] | 21 | use anyhow::{ensure, Context, Result}; |
Alice Wang | 0cafa14 | 2022-09-23 15:17:02 +0000 | [diff] [blame] | 22 | use std::io::{Read, Seek}; |
| 23 | |
| 24 | use crate::algorithms::SignatureAlgorithmID; |
| 25 | use 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 |
| 32 | pub 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 Wang | f27626a | 2022-09-27 12:36:22 +0000 | [diff] [blame] | 37 | 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 Wang | 0cafa14 | 2022-09-23 15:17:02 +0000 | [diff] [blame] | 42 | if verify { |
Alice Wang | f27626a | 2022-09-27 12:36:22 +0000 | [diff] [blame] | 43 | let computed_digest = sections.compute_digest(strongest_algorithm_id)?; |
Alice Wang | 0cafa14 | 2022-09-23 15:17:02 +0000 | [diff] [blame] | 44 | ensure!( |
| 45 | computed_digest == extracted_digest.as_ref(), |
| 46 | "Computed digest does not match the extracted digest." |
| 47 | ); |
| 48 | } |
Alice Wang | f27626a | 2022-09-27 12:36:22 +0000 | [diff] [blame] | 49 | Ok((strongest_algorithm_id, extracted_digest)) |
Alice Wang | 0cafa14 | 2022-09-23 15:17:02 +0000 | [diff] [blame] | 50 | } |