Start to generate private key

This commit is contained in:
Pierre HUBERT 2024-07-27 16:34:41 +02:00
parent 0c6c0f4a7f
commit 402edb44d5
3 changed files with 45 additions and 15 deletions

View File

@ -1,6 +1,7 @@
#include "crypto.h"
#include "system.h"
#include <string.h>
#include <mbedtls/build_info.h>
#include <mbedtls/platform.h>
#include <mbedtls/entropy.h>
@ -16,6 +17,8 @@
bool crypto_gen_priv_key()
{
// TODO : check if key exists in memory
int ret = 1;
const char *pers = "ecdsa";
@ -23,11 +26,13 @@ bool crypto_gen_priv_key()
mbedtls_entropy_context entropy;
mbedtls_entropy_init(&entropy);
mbedtls_ecdsa_context ctx_sign;
mbedtls_ecdsa_init(&ctx_sign);
mbedtls_pk_context key;
mbedtls_pk_init(&key);
mbedtls_ctr_drbg_context ctr_drbg;
mbedtls_ctr_drbg_init(&ctr_drbg);
printf("Seed Mbedtls\n");
if ((ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy,
(const unsigned char *)pers,
strlen(pers))) != 0)
@ -36,16 +41,39 @@ bool crypto_gen_priv_key()
reboot();
}
// Generate private key
if ((ret = mbedtls_ecdsa_genkey(&ctx_sign, ECPARAMS,
mbedtls_ctr_drbg_random, &ctr_drbg)) != 0)
printf("PK info from type\n");
if ((ret = mbedtls_pk_setup(&key, mbedtls_pk_info_from_type(MBEDTLS_PK_ECKEY))) != 0)
{
mbedtls_printf(" failed\n ! mbedtls_ecdsa_genkey returned %d\n", ret);
mbedtls_printf(" failed\n ! mbedtls_pk_setup returned -0x%04x", (unsigned int)-ret);
reboot();
}
mbedtls_pk_context key_ctx;
mbedtls_ecp_gen_keypair
// Generate private key
printf("Generate private key\n");
ret = mbedtls_ecp_gen_key(ECPARAMS,
mbedtls_pk_ec(key),
mbedtls_ctr_drbg_random, &ctr_drbg);
if (ret != 0)
{
mbedtls_printf(" failed\n ! mbedtls_ecp_gen_key returned -0x%04x",
(unsigned int)-ret);
reboot();
}
mbedtls_pk_write_key_pem()
// Show private key
printf("Show private key\n");
unsigned char *key_buff = malloc(16000);
memset(key_buff, 0, 16000);
if ((ret = mbedtls_pk_write_key_pem(&key, key_buff, 16000)) != 0)
{
mbedtls_printf(" failed\n ! mbedtls_pk_write_key_pem returned -0x%04x",
(unsigned int)-ret);
reboot();
}
printf("%s", key_buff);
free(key_buff);
printf("done\n");
return true;
}

View File

@ -13,6 +13,8 @@ extern "C"
/**
* Generate device private key, if required
*
* @returns true if a key was generated, false otherwise
*/
bool crypto_gen_priv_key();

View File

@ -4,6 +4,7 @@
#include "dev_name.h"
#include "storage.h"
#include "system.h"
#include "crypto.h"
void app_main(void)
{
@ -20,15 +21,14 @@ void app_main(void)
printf("Generated a new device name\n");
}
char *name = dev_name();
printf("Dev name: %s\n", name);
free(name);
if (crypto_gen_priv_key())
{
printf("Generated device private key!\n");
}
char *name = dev_name();
printf("Dev name: %s\n", name);
free(name);
fflush(stdout);
esp_restart();
reboot();
}