ESP32+Arduino IDE+Mbed TLS realizes generating pem public key and private key and testing encryption and decryption

Due to my limited technology
The following code implements the RSA algorithm in the hardware environment of ESP32, which provides the possibility for the encrypted communication of ESP32 in the next step. ESP32C3 refers to the technical manual, which contains the hardware RSA calculator, but because there is no tutorial document code porting, the only register I can find for the time being Address, although a soft encryption may be 1 second faster than a hard encryption, but if you go to make up the middle layer by yourself, it may take a month or even a few months.
The following code is written for ChatGpt. Tested to work, generated key pairs match. However, I cannot fully analyze the specific working process due to my limited ability. For environment installation, refer to the tutorial at https://blog.csdn.net/imba_wolf/article/details/122417540

#include <mbedtls/pk.h>
#include <mbedtls/rsa.h>
#include <mbedtls/entropy.h>
#include <mbedtls/ctr_drbg.h>
#include <mbedtls/error.h>
#include <mbedtls/pem.h>

void setup() {<!-- -->
  Serial.begin(115200);

  // Initialize the random number generator
  mbedtls_entropy_context entropy;
  mbedtls_ctr_drbg_context ctr_drbg;
  mbedtls_entropy_init( &entropy);
  mbedtls_ctr_drbg_init( &ctr_drbg);

  const char *pers = "rsa_key_generation";
  mbedtls_ctr_drbg_seed( &ctr_drbg, mbedtls_entropy_func, &entropy,
                        (const unsigned char *)pers, strlen(pers));

  // Initialize the RSA context
  mbedtls_rsa_context rsa;
  mbedtls_rsa_init( &rsa, MBEDTLS_RSA_PKCS_V15, 0);

  // generate RSA key pair
  int ret = mbedtls_rsa_gen_key( &rsa, mbedtls_ctr_drbg_random, &ctr_drbg, 2048, 65537);
  if (ret == 0) {<!-- -->
    Serial.println("RSA key generation successful!");

    // Create and initialize the PK context
    mbedtls_pk_context pk;
    mbedtls_pk_init( &pk);

    // Set the type of PK context to RSA
    mbedtls_pk_setup( &pk, mbedtls_pk_info_from_type(MBEDTLS_PK_RSA));

    // Get the RSA field of the PK context and set the RSA context
    mbedtls_rsa_copy(mbedtls_pk_rsa(pk), &rsa);

    // output public key
    unsigned char pubKeyPem[1024];
    size_t pubKeyPemLen = 0;
    ret = mbedtls_pk_write_pubkey_pem( &pk, pubKeyPem, sizeof(pubKeyPem));
    if (ret == 0) {<!-- -->
      Serial.println("Public key in PEM format:");
      Serial.println((char *)pubKeyPem);
    } else {<!-- -->
      char errorBuf[100];
      mbedtls_strerror(ret, errorBuf, sizeof(errorBuf));
      Serial.print("Failed to convert public key to PEM format! Error code: ");
      Serial. println(ret);
      Serial.print("Error message: ");
      Serial. println(errorBuf);
    }

    // output private key
    unsigned char privKeyPem[2048];
    size_t privKeyPemLen = 0;
    ret = mbedtls_pk_write_key_pem( &pk, privKeyPem, sizeof(privKeyPem));
    if (ret == 0) {<!-- -->
      Serial.println("Private key in PEM format:");
      Serial.println((char *)privKeyPem);
    } else {<!-- -->
      char errorBuf[100];
      mbedtls_strerror(ret, errorBuf, sizeof(errorBuf));
      Serial.print("Failed to convert private key to PEM format! Error code: ");
      Serial. println(ret);
      Serial.print("Error message: ");
      Serial. println(errorBuf);
    }

    // encryption and decryption test
    const char *plaintext = "Hello, World!";
    unsigned char ciphertext[256];
    unsigned char decrypted[256];
    size_t ciphertextLen = 0;
    size_t decryptedLen = 0;

    // encryption
    ret = mbedtls_rsa_pkcs1_encrypt(mbedtls_pk_rsa(pk), mbedtls_ctr_drbg_random, &ctr_drbg, MBEDTLS_RSA_PUBLIC, strlen(plaintext), (const unsigned char *)plaintext, ciphertext);
    if (ret == 0) {<!-- -->
      Serial.println("Encryption successful!");
      ciphertextLen = mbedtls_rsa_get_len(mbedtls_pk_rsa(pk));
      Serial.print("Ciphertext: ");
      for (size_t i = 0; i < ciphertextLen; i ++ ) {<!-- -->
        Serial.print(ciphertext[i], HEX);
        Serial.print(" ");
      }
      Serial. println();
    } else {<!-- -->
      char errorBuf[100];
      mbedtls_strerror(ret, errorBuf, sizeof(errorBuf));
      Serial.print("Encryption failed! Error code: ");
      Serial. println(ret);
      Serial.print("Error message: ");
      Serial. println(errorBuf);
    }

    // decrypt
    ret = mbedtls_rsa_pkcs1_decrypt(mbedtls_pk_rsa(pk), mbedtls_ctr_drbg_random, &ctr_drbg, MBEDTLS_RSA_PRIVATE, &decryptedLen, ciphertext, decrypted, sizeof(decrypted));
    if (ret == 0) {<!-- -->
      Serial.println("Decryption successful!");
      Serial.print("Plaintext: ");
      for (size_t i = 0; i < decryptedLen; i ++ ) {<!-- -->
        Serial.print((char)decrypted[i]);
      }
      Serial. println();
    } else {<!-- -->
      char errorBuf[100];
      mbedtls_strerror(ret, errorBuf, sizeof(errorBuf));
      Serial.print("Decryption failed! Error code: ");
      Serial. println(ret);
      Serial.print("Error message: ");
      Serial. println(errorBuf);
    }
  } else {<!-- -->
    char errorBuf[100];
    mbedtls_strerror(ret, errorBuf, sizeof(errorBuf));
    Serial.print("RSA key generation failed! Error code: ");
    Serial. println(ret);
    Serial.print("Error message: ");
    Serial. println(errorBuf);
  }

  // clean up resources
  mbedtls_rsa_free( &rsa);
  mbedtls_ctr_drbg_free( &ctr_drbg);
  mbedtls_entropy_free( &entropy);
}

void loop() {<!-- -->
  // empty loop
}

The last serial port output

Public key in PEM format:
—–BEGIN PUBLIC KEY—–
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxnFTSROaiPS0edTcJZzo
07cnZXNLjZ75KbiJGSThmMq/KmrKO8SDP4Ak/Zl666719nR5XxrxKI3Pco0FVWIy
PSrIseoS/lLa/XCXsO5gRXXm1QHT + BZehx/2azoLD0Pn/YmRQ6elHoMMyNpAqfTs
sasO2e/qt3SfgjNMTii3DgIoBe1hYGrBFmPoH6cgZSZ8mV5pZ89FxD2qvRlBtZgb
D+XYuDrGRn5ZNyrgD4jyNV4kkazs2ePfBVczVNXbq33olmH5L8npCnfP1W3Qw+Er
vhhBpu63BoJQIl82E971wszIwJeZ2OMPUOsNfK1F3AKF84Ob52mPUd5Y/Xr9NgsX
QIDAQAB
—–END PUBLIC KEY—–

Private key in PEM format:
—–BEGIN RSA PRIVATE KEY—–
MIIEowIBAAKCAQEAxnFTSROaiPS0edTcJZzo07cnZXNLjZ75KbiJGSThmMq/KmrK
O8SD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p98X + RAq52F/4SrDIAm6q0TPw4lK0A52mpP0
/MUXSAS88OLoomJjSO0BrZFm1OCLLouPQxB6eXL4UAeGpY/abmRaCLmtalgTzI5G
JIRw6IpnTwPaRiPy5sXJYQKBgDDtHf972YwPyIhE10pgQU8JjqZCCUqayiYLBYMP
DKReuFsashS/A9/VE7i0P4HCMplnkLGU9Q0u5jBV3jYzQlZyChWe39qTjc4qLQpS
VFG0iF7Y + DAj5ARmhoZT4IS64mWJuATGUAe5E9Pe0UUld9NuZ29TW2KaX1SQqx6A
1UpvAoGBAKjmhUx3YuyTXjXAi2YcihgwLJskqIcUFxpIJ6Q5TaIB8h1ae3Jmmx3f
Fe9LiCDisl4VgbtU3jwwf2EO1zpkyuMFL/shfcENjyP0V5Yjrbr2hgS9o0x9EBlY
aAlrlH + pmGlOKE03A/XPZj330l0CbRrsJe5xQyarjpmhi6r0WhNe
—–END RSA PRIVATE KEY—–

Encryption successful!
Ciphertext: B9 20 D7 86 33 F3 8F D0 3F AA DC FA BD 3D A3 9D E4 BD 8F B6 69 2C B9 5E 7D D2 4B F4 B2 87 35 E9 CB DF 79 1A E1 AD 66 60 CB 69 70 78 5B 82 25 8C 7E BA E0 73 C0 C 38 C1 85 95 20 12 50 2E 17 D3 45 6B 67 8A BA DE 34 5D 64 E3 F0 BF 22 60 B2 3F 63 FD F0 5F DD 27 4B A5 7E 37 EE A1 AA 12 9F 53 33 CF CB 35 DB 50 9D E1 24 91 DA DB C3 37 DF 22 43 DC 6C B8 7F 20 80 AB 4 B9 69 C9 DE B8 1A E8 24 C3 EA 31 80 D8 32 C0 CB 9E AD EA 2B D D 69 2B A D4 31 89 CF A 69 50 D0 A5 8E D9 CD 3A 1A 92 EB D1 28 A0 CA FE D7 AC B3 64 72 C4 1D 5 E1 50 BF 82 20 A4 0 71 DA 27 2F 2 96 18 C 53 10 A8 1 60 82 91 EC 1D B9 DB 8D 40 EC 62 A0 68 DD 2C 28 89 3D DC ED 2A 30 E6 73 28 91 22 33 87 96 28 52 A5 12 A2 3B 2B 5B E4 57 87 FA C2 B3 4F 74 2 D B 32 F2 F BD DE FC 7 A2
Decryption successful!
Plaintext: Hello, World!