cli/
template.rs

1// SPDX-License-Identifier: GPL-3-0-or-later
2// Copyright (c) 2025 Opinsys Oy
3
4use crate::key::{Alg, AlgInfo};
5use tpm2_protocol::{
6    basic::TpmBuffer,
7    data::{
8        Tpm2bDigest, TpmAlgId, TpmaObject, TpmsEccParms, TpmsKeyedhashParms, TpmsRsaParms,
9        TpmtEccScheme, TpmtKdfScheme, TpmtKeyedhashScheme, TpmtPublic, TpmtRsaScheme,
10        TpmtSymDefObject, TpmuKeyedhashScheme, TpmuPublicId, TpmuPublicParms, TpmuSymKeyBits,
11        TpmuSymMode,
12    },
13};
14
15/// Builds a `TpmtPublic` template for creating new objects.
16///
17/// Centralizes the logic for constructing the public area of a TPM object,
18/// handling RSA, ECC, and `KeyedHash` types based on the provided `Alg`.
19#[must_use]
20pub fn build_public(
21    alg_desc: &Alg,
22    auth_policy: Tpm2bDigest,
23    object_attributes: TpmaObject,
24) -> TpmtPublic {
25    let symmetric = TpmtSymDefObject {
26        algorithm: TpmAlgId::Aes,
27        key_bits: TpmuSymKeyBits::Aes(128),
28        mode: TpmuSymMode::Aes(TpmAlgId::Cfb),
29    };
30
31    let (parameters, unique) = match alg_desc.params {
32        AlgInfo::Rsa { key_bits } => (
33            TpmuPublicParms::Rsa(TpmsRsaParms {
34                symmetric,
35                scheme: TpmtRsaScheme::default(),
36                key_bits,
37                exponent: 0,
38            }),
39            TpmuPublicId::Rsa(TpmBuffer::default()),
40        ),
41        AlgInfo::Ecc { curve_id } => (
42            TpmuPublicParms::Ecc(TpmsEccParms {
43                symmetric,
44                scheme: TpmtEccScheme::default(),
45                curve_id,
46                kdf: TpmtKdfScheme::default(),
47            }),
48            TpmuPublicId::Ecc(tpm2_protocol::data::TpmsEccPoint::default()),
49        ),
50        AlgInfo::KeyedHash => (
51            TpmuPublicParms::KeyedHash(TpmsKeyedhashParms {
52                scheme: TpmtKeyedhashScheme {
53                    scheme: TpmAlgId::Null,
54                    details: TpmuKeyedhashScheme::Null,
55                },
56            }),
57            TpmuPublicId::KeyedHash(TpmBuffer::default()),
58        ),
59    };
60
61    TpmtPublic {
62        object_type: alg_desc.object_type,
63        name_alg: alg_desc.name_alg,
64        object_attributes,
65        auth_policy,
66        parameters,
67        unique,
68    }
69}