SolarEnergy/esp32_device/main/crypto.c

92 lines
2.5 KiB
C
Raw Normal View History

2024-07-27 14:15:35 +00:00
#include "crypto.h"
#include "system.h"
2024-08-15 11:09:01 +00:00
#include "constants.h"
#include "storage.h"
2024-07-27 14:15:35 +00:00
2024-07-27 14:34:41 +00:00
#include <string.h>
2024-07-27 14:15:35 +00:00
#include <mbedtls/build_info.h>
#include <mbedtls/platform.h>
#include <mbedtls/entropy.h>
#include <mbedtls/ctr_drbg.h>
#include <mbedtls/ecdsa.h>
#include <mbedtls/sha256.h>
#include <mbedtls/pk.h>
#define ECPARAMS MBEDTLS_ECP_DP_SECP256R1
bool crypto_gen_priv_key()
{
2024-07-27 14:34:41 +00:00
// TODO : check if key exists in memory
2024-07-27 14:15:35 +00:00
int ret = 1;
const char *pers = "ecdsa";
mbedtls_entropy_context entropy;
mbedtls_entropy_init(&entropy);
2024-07-27 14:34:41 +00:00
mbedtls_pk_context key;
mbedtls_pk_init(&key);
2024-07-27 14:15:35 +00:00
mbedtls_ctr_drbg_context ctr_drbg;
2024-07-27 14:34:41 +00:00
mbedtls_ctr_drbg_init(&ctr_drbg);
2024-07-27 14:15:35 +00:00
2024-07-27 14:34:41 +00:00
printf("Seed Mbedtls\n");
2024-07-27 14:15:35 +00:00
if ((ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy,
(const unsigned char *)pers,
strlen(pers))) != 0)
{
mbedtls_printf(" failed\n ! mbedtls_ctr_drbg_seed returned %d\n", ret);
reboot();
}
2024-07-27 14:34:41 +00:00
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_pk_setup returned -0x%04x", (unsigned int)-ret);
reboot();
}
2024-07-27 14:15:35 +00:00
// Generate private key
2024-07-27 14:34:41 +00:00
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();
}
2024-08-15 11:09:01 +00:00
// Export private key
printf("Export private key\n");
unsigned char *key_buff = malloc(PRV_KEY_DER_MAX_BYTES);
if ((ret = mbedtls_pk_write_key_der(&key, key_buff, PRV_KEY_DER_MAX_BYTES)) < 1)
{
mbedtls_printf(" failed\n ! mbedtls_pk_write_key_der returned -0x%04x",
(unsigned int)-ret);
reboot();
}
storage_set_priv_key(key_buff + PRV_KEY_DER_MAX_BYTES - ret, ret);
return true;
}
/**
* // Show private key
2024-07-27 14:34:41 +00:00
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)
2024-07-27 14:15:35 +00:00
{
2024-07-27 14:34:41 +00:00
mbedtls_printf(" failed\n ! mbedtls_pk_write_key_pem returned -0x%04x",
(unsigned int)-ret);
2024-07-27 14:15:35 +00:00
reboot();
}
2024-07-27 14:34:41 +00:00
printf("%s", key_buff);
free(key_buff);
printf("done\n");
2024-08-15 11:09:01 +00:00
*/