diff --git a/platforms/common/include/px4_platform_common/crypto_backend.h b/platforms/common/include/px4_platform_common/crypto_backend.h index ae63875560..1b1df6e87b 100644 --- a/platforms/common/include/px4_platform_common/crypto_backend.h +++ b/platforms/common/include/px4_platform_common/crypto_backend.h @@ -73,6 +73,7 @@ size_t keystore_get_key(keystore_session_handle_t handle, uint8_t idx, uint8_t * /* * Store a key persistently into the keystore + * handle: a handle to an open keystore * idx: key index in keystore * key: pointer to the key * key_size: size of the key @@ -105,6 +106,17 @@ crypto_session_handle_t crypto_open(px4_crypto_algorithm_t algorithm); void crypto_close(crypto_session_handle_t *handle); +/* + * Generate a key + * handle: Open handle for the crypto session. The key will be generated for + * the crypto algorithm used by this session + * idx: The key index, by which the key can be used + * persistent: if set to "true", the key will be stored into the keystore + */ +bool crypto_generate_key(crypto_session_handle_t handle, + uint8_t idx, + bool persistent); + /* * Get a key from keystore, possibly encrypted * diff --git a/platforms/common/px4_sw_crypto/sw_crypto/crypto.c b/platforms/common/px4_sw_crypto/sw_crypto/crypto.c index 04a2fea021..8d8e0cd7ed 100644 --- a/platforms/common/px4_sw_crypto/sw_crypto/crypto.c +++ b/platforms/common/px4_sw_crypto/sw_crypto/crypto.c @@ -42,6 +42,7 @@ #include #include +#include #include #include @@ -295,6 +296,48 @@ bool crypto_encrypt_data(crypto_session_handle_t handle, return ret; } +bool crypto_generate_key(crypto_session_handle_t handle, + uint8_t idx, bool persistent) +{ + bool ret = false; + + if (idx >= KEY_CACHE_LEN) { + return false; + } + + switch (handle.algorithm) { + case CRYPTO_XCHACHA20: + if (key_cache[idx].key_size < 32) { + if (key_cache[idx].key_size > 0) { + SECMEM_FREE(key_cache[idx].key); + key_cache[idx].key_size = 0; + } + + key_cache[idx].key = SECMEM_ALLOC(32); + } + + if (key_cache[idx].key) { + key_cache[idx].key_size = 32; + px4_get_secure_random(key_cache[idx].key, 32); + ret = true; + + } else { + key_cache[idx].key_size = 0; + } + + break; + + default: + break; + } + + if (ret && persistent) { + keystore_put_key(handle.keystore_handle, idx, key_cache[idx].key, key_cache[idx].key_size); + } + + return ret; +} + bool crypto_get_encrypted_key(crypto_session_handle_t handle, uint8_t key_idx, uint8_t *key,