The key creation functions (psa_generate_key
, psa_import_key
, psa_key_derivation_output_key
) either create a key in memory (volatile key) or in storage (persistent key) depending on the key attributes. Keys are volatile by default. To make a key persistent, call psa_set_key_id
before creating the key. The key id that you pick is the key's persistent name. To use the key in the future, just use that key id.
#define KEY_ID 42
int generate_key() {
psa_key_attributes_t attributes = {0};
psa_set_key_type(&attributes, PSA_KEY_TYPE_AES);
psa_set_key_bits(&attributes, 128);
psa_set_key_usage(&attributes, PSA_KEY_USAGE_ENCRYPT | PSA_KEY_USAGE_DECRYPT);
psa_set_key_algorithm(&attributes, PSA_ALG_GCM); // or whatever
psa_set_key_id(&attributes, KEY_ID);
psa_key_id_t key_id;
psa_status_t status = psa_generate_key(&attributes, &key_id);
if (status != PSA_SUCCESS) goto error;
assert(key_id == KEY_ID); // for a persistent key, the key_id output from key creation is redundant: it's always the key id requested in the attributes
…
}
int use_key() {
psa_status_t status = psa_cipher_encrypt(KEY_ID, ...);
if (status != PSA_SUCCESS) goto error;
…
}