tss-keyfile 0.1.5

Decoding of TPM 2.0 TSS Keyfiles from PEM/DER/(ASN.1)
Documentation

TPM 2.0 TSS Keyfile Rust Library

Decoding of TPM 2.0 TSS Keyfiles from PEM/DER/(ASN.1)

Keyfiles as generated by e.g. tm2tss-genkey

Implements specification: https://www.hansenpartnership.com/draft-bottomley-tpm2-keys.html

Reading a Keyfile in PEM format

let pem: Vec<u8> = std::fs::read("keyfile.tss.pem").unwrap();
let key = TPMKey::try_from_pem(&pem).unwrap();
println!("{key}");

Reading a Keyfile in DER format

let der: Vec<u8> = std::fs::read("keyfile.tss.der").unwrap();
let key = TPMKey::try_from_der(&der).unwrap();
println!("{key}");

TSS ESAPI usage example

fn load_private_key(
    tcti: TctiNameConf,
    keyfile_path: &Path,
) -> Result<KeyHandle, Box<dyn std::error::Error>> {
    // Load and parse the TSS2 keyfile
    let pem: Vec<u8> = std::fs::read(keyfile_path).unwrap();
    let tpmkey = tss_keyfile::TPMKey::try_from_pem(&pem).unwrap();

    // unmarshall `TPM2B_PRIVATE, TPM2B_PUBLIC` - `OctetSting`s and the persistent parent handle
    let privkey = Private::try_from(&tpmkey.privkey[2..])?;
    let pubkey_buffer = PublicBuffer::unmarshall(&tpmkey.pubkey.to_vec())?;
    let pubkey = Public::try_from(pubkey_buffer)?;
    let parent = PersistentTpmHandle::new(tpmkey.parent)?;

    // Create TPM context
    let mut context = Context::new(tcti)?;

    // Create ESYS handle mapping for the persistent parent handle
    let mapped_parent_obj = context.tr_from_tpm_public(parent.into())?;
    let mapped_parent_handle = KeyHandle::from(mapped_parent_obj);

    // Set up session and load key
    context.set_sessions((Some(AuthSession::Password), None, None));
    let key_handle = context.load(mapped_parent_handle, privkey, pubkey)?;

    Ok(key_handle)
}