Saving public/private portions of key to filesystem for long-term storage #542
-
I am trying to replicate the results of the following example from the I am unsure how to write the generated public/private keys to files for long-term storage (I have successfully generated the public/private portions using |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Solved, example code that tries to load a public/private keypair from a file before generating a new one: fn create_signing_handle(context: &mut Context, primary_key_handle: KeyHandle) -> KeyHandle {
let pub_file = File::open("key.pub");
let priv_file = File::open("key.priv");
if let (Ok(mut pub_file), Ok(mut priv_file)) = (pub_file, priv_file) {
let mut buf = vec![];
let _ = pub_file.read_to_end(&mut buf);
let pub_key = Public::unmarshall(&buf).unwrap();
buf.clear();
let _ = priv_file.read_to_end(&mut buf);
let priv_key = Private::try_from(buf.clone()).unwrap();
let handle = context
.execute_with_nullauth_session(|ctx| ctx.load(primary_key_handle, priv_key, pub_key))
.unwrap();
return handle;
}
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(false)
.with_sign_encrypt(true)
// Note that we don't set the key as restricted.
.build()
.expect("Failed to build object attributes");
let rsa_params = PublicRsaParametersBuilder::new()
.with_scheme(RsaScheme::Null)
.with_key_bits(RsaKeyBits::Rsa2048)
.with_exponent(RsaExponent::default())
.with_is_signing_key(true)
// disallow decryption since allowing both is vulnerable to attacks
.with_is_decryption_key(false)
.with_restricted(false)
.build()
.expect("Failed to build rsa parameters");
let key_pub = PublicBuilder::new()
.with_public_algorithm(PublicAlgorithm::Rsa)
.with_name_hashing_algorithm(HashingAlgorithm::Sha512)
.with_object_attributes(object_attributes)
.with_rsa_parameters(rsa_params)
.with_rsa_unique_identifier(PublicKeyRsa::default())
.build()
.unwrap();
let (private, public) = context
.execute_with_nullauth_session(|ctx| {
ctx.create(primary_key_handle, key_pub, None, None, None, None)
.map(|key| (key.out_private, key.out_public))
})
.unwrap();
let key_handle = context
.execute_with_nullauth_session(|ctx| {
ctx.load(primary_key_handle, private.clone(), public.clone())
})
.unwrap();
let mut pub_file = File::create("key.pub").unwrap();
pub_file.write_all(&public.marshall().unwrap()).unwrap();
let mut priv_file = File::create("key.priv").unwrap();
priv_file.write_all(&private).unwrap();
key_handle
} Most notable is the beginning of the function which loads from two files, |
Beta Was this translation helpful? Give feedback.
Solved, example code that tries to load a public/private keypair from a file before generating a new one: