Skip to main content

tss_keyfile/
lib.rs

1//! All TPM 2.0 keys consist of two binary pieces, a public part, which can be parsed
2//! according to the TPM specification for TPM2B_PUBLIC [TPM2.0] and a private part,
3//! which is cryptographically sealed in such a way as to be only readable on the TPM
4//! that created it.
5
6#![cfg_attr(not(test), no_std)]
7extern crate alloc;
8
9use alloc::{string::String, vec::Vec};
10
11#[cfg(feature = "pem")]
12pub use pem_rfc7468::Error as PemError;
13
14pub use rasn::error::DecodeError as RasnDecodeError;
15pub use rasn::error::EncodeError as RasnEncodeError;
16
17// modules
18mod tpmkey;
19pub use tpmkey::OID_TPMKEY_IMPORTABLE;
20pub use tpmkey::OID_TPMKEY_LOADABLE;
21pub use tpmkey::OID_TPMKEY_SEALED;
22pub use tpmkey::TPMAuthPolicy;
23pub use tpmkey::TPMKey;
24pub use tpmkey::TPMKeyType;
25pub use tpmkey::TPMPolicy;
26
27#[derive(thiserror::Error, Debug)]
28pub enum Error {
29    #[error("Missing a secret")]
30    MissingSecret,
31    #[error("Should not have a secret")]
32    UnexpectedSecret,
33    #[error("DER decoding error: {0}")]
34    DerDecodeError(#[from] RasnDecodeError),
35    #[error("DER encoding error: {0}")]
36    DerEncodeError(#[from] RasnEncodeError),
37    #[error("OID is not a TSS2 PRIVATE KEY")]
38    NoTss2PrivateKey,
39    #[error("Key has an invalid parent handle: 0x{0}")]
40    InvalidParentHandle(String),
41    #[cfg(feature = "pem")]
42    #[error("PEM decoding error: {0}")]
43    PemDecodeError(pem_rfc7468::Error),
44    #[error("PEM data is not a TSS2 PRIVATE KEY")]
45    PemNoTss2PrivateKey,
46}
47
48#[cfg(feature = "pem")]
49impl From<PemError> for Error {
50    fn from(err: PemError) -> Self {
51        Self::PemDecodeError(err)
52    }
53}
54
55/// decode PEM, check label, return copy as DER
56pub fn checked_pem_to_der(pem: &[u8]) -> Result<Vec<u8>, crate::Error> {
57    let (label, der) = pem_rfc7468::decode_vec(pem)?;
58
59    if label != "TSS2 PRIVATE KEY" {
60        return Err(crate::Error::PemNoTss2PrivateKey);
61    }
62    Ok(der)
63}