cancel
Showing results for 
Search instead for 
Did you mean: 

Crypto lib - how to load .pem file? I have to use a public key provided to me in a .pem file to encrypt an array of bytes. What is the easiest way to compile or include the .pem file into STM32CubeIDE project as an array of bytes?

SLevi.1
Associate III

Also, the crypto functions require a key made up of an exponent and a modulus. The examples only show these as two separate arrays. How do I get from a single array I have hopefully included from the pem file into these two separate arrays? What is the format?

As a separate task, does anyone have any example of how to decrypt a large amount of data using a private key? The large amount will be read from a flash chip in multiple 512 byte chunks.

2 REPLIES 2
Markus GIRDLAND
ST Employee

Hello there,

There is some examples using .pem files in the FW pack AWS IoT software expansion for STM32Cube (UM2178). Hopefully something in that pack that you can use to get a good picture on how to load .pem files.

Pavel A.
Evangelist III

With python, something like below:

from Crypto.PublicKey import RSA  # Crypto is PyCryptoDome
 
KEY_RSA_LENGTH = 2048  # or 1024.... key length in bits
 
def ExportPublicKey(pem_file, bin_file) :
    with open(pem_file, 'rb') as pf:
        key = RSA.importKey(pf.read())
 
    with open(bin_file, 'wb') as bf:
        modulus_len = KEY_RSA_LENGTH // 8
        bf.write(key.n.to_bytes(modulus_len, byteorder='big'))
        bf.write(key.e.to_bytes(3, byteorder='big'))

The written binary data can be used with the cryptolib.

struct {
   uint8_t modulus[KEY_RSA_LENGTH/8];
   uint8_t exponent[3];
} pubkey;