use tss_esapi::{
Context, TctiNameConf,
attributes::ObjectAttributesBuilder,
interface_types::{
algorithm::{HashingAlgorithm, PublicAlgorithm},
reserved_handles::Hierarchy,
},
structures::{
CreatePrimaryKeyResult, Digest, KeyedHashScheme, PublicBuilder, PublicKeyedHashParameters,
SensitiveData, SymmetricCipherParameters, SymmetricDefinitionObject,
},
};
use std::convert::TryFrom;
fn main() {
let mut context = Context::new(
TctiNameConf::from_environment_variable()
.expect("Failed to get TCTI / TPM2TOOLS_TCTI from environment. Try `export TCTI=device:/dev/tpmrm0`"),
)
.expect("Failed to create Context");
let primary = create_primary(&mut context);
let sensitive_data = SensitiveData::try_from(vec![
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 26, 27, 28, 29, 30, 31,
])
.unwrap();
let object_attributes = ObjectAttributesBuilder::new()
.with_fixed_tpm(true)
.with_fixed_parent(true)
.with_st_clear(true)
.with_user_with_auth(true)
.build()
.expect("Failed to build object attributes");
let key_pub = PublicBuilder::new()
.with_public_algorithm(PublicAlgorithm::KeyedHash)
.with_name_hashing_algorithm(HashingAlgorithm::Sha256)
.with_object_attributes(object_attributes)
.with_keyed_hash_parameters(PublicKeyedHashParameters::new(KeyedHashScheme::Null))
.with_keyed_hash_unique_identifier(Digest::default())
.build()
.unwrap();
let (enc_private, public) = context
.execute_with_nullauth_session(|ctx| {
ctx.create(
primary.key_handle,
key_pub,
None,
Some(sensitive_data.clone()),
None,
None,
)
.map(|key| (key.out_private, key.out_public))
})
.unwrap();
let unsealed = context
.execute_with_nullauth_session(|ctx| {
let sealed_data_object = ctx
.load(primary.key_handle, enc_private.clone(), public.clone())
.unwrap();
ctx.unseal(sealed_data_object.into())
})
.unwrap();
println!("sensitive_data = {sensitive_data:?}");
println!("unsealed_data = {unsealed:?}");
assert_eq!(unsealed, sensitive_data);
}
fn create_primary(context: &mut Context) -> CreatePrimaryKeyResult {
let object_attributes = ObjectAttributesBuilder::new()
.with_fixed_tpm(true)
.with_fixed_parent(true)
.with_st_clear(false)
.with_sensitive_data_origin(true)
.with_user_with_auth(true)
.with_decrypt(true)
.with_restricted(true)
.build()
.expect("Failed to build object attributes");
let primary_pub = PublicBuilder::new()
.with_public_algorithm(PublicAlgorithm::SymCipher)
.with_name_hashing_algorithm(HashingAlgorithm::Sha256)
.with_object_attributes(object_attributes)
.with_symmetric_cipher_parameters(SymmetricCipherParameters::new(
SymmetricDefinitionObject::AES_128_CFB,
))
.with_symmetric_cipher_unique_identifier(Digest::default())
.build()
.unwrap();
context
.execute_with_nullauth_session(|ctx| {
ctx.create_primary(Hierarchy::Owner, primary_pub, None, None, None, None)
})
.unwrap()
}