blob: 066d4a1e0a764f8fca7d3da07b882f7a7f1abce6 [file] [log] [blame]
Rajesh Nyamagoudc946cc42022-04-12 22:49:11 +00001// Copyright 2022, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use keystore2_test_utils::key_generations::Error;
16
17#[cxx::bridge]
18mod ffi {
19 struct CxxResult {
20 data: Vec<u8>,
21 error: i32,
22 }
23
24 unsafe extern "C++" {
25 include!("ffi_test_utils.hpp");
26 fn validateCertChain(cert_buf: Vec<u8>, cert_len: u32, strict_issuer_check: bool) -> bool;
27 fn createWrappedKey(
28 encrypted_secure_key: Vec<u8>,
29 encrypted_transport_key: Vec<u8>,
30 iv: Vec<u8>,
31 tag: Vec<u8>,
32 ) -> CxxResult;
33 fn buildAsn1DerEncodedWrappedKeyDescription() -> CxxResult;
34 }
35}
36
37/// Validate given certificate chain.
38pub fn validate_certchain(cert_buf: &[u8]) -> Result<bool, Error> {
39 if ffi::validateCertChain(cert_buf.to_vec(), cert_buf.len().try_into().unwrap(), true) {
40 return Ok(true);
41 }
42
43 Err(Error::ValidateCertChainFailed)
44}
45
46fn get_result(result: ffi::CxxResult) -> Result<Vec<u8>, Error> {
47 if result.error == 0 && !result.data.is_empty() {
48 Ok(result.data)
49 } else {
50 Err(Error::DerEncodeFailed)
51 }
52}
53
54/// Creates wrapped key material to import in ASN.1 DER-encoded data corresponding to
55/// `SecureKeyWrapper`. See `IKeyMintDevice.aidl` for documentation of the `SecureKeyWrapper`
56/// schema.
57pub fn create_wrapped_key(
58 encrypted_secure_key: &[u8],
59 encrypted_transport_key: &[u8],
60 iv: &[u8],
61 tag: &[u8],
62) -> Result<Vec<u8>, Error> {
63 get_result(ffi::createWrappedKey(
64 encrypted_secure_key.to_vec(),
65 encrypted_transport_key.to_vec(),
66 iv.to_vec(),
67 tag.to_vec(),
68 ))
69}
70
71/// Creates ASN.1 DER-encoded data corresponding to `KeyDescription` schema.
72/// See `IKeyMintDevice.aidl` for documentation of the `KeyDescription` schema.
73/// Below mentioned key parameters are used -
74/// Algorithm: AES-256
75/// Padding: PKCS7
76/// Blockmode: ECB
77/// Purpose: Encrypt, Decrypt
78pub fn create_wrapped_key_additional_auth_data() -> Result<Vec<u8>, Error> {
79 get_result(ffi::buildAsn1DerEncodedWrappedKeyDescription())
80}