Mbed forum

RSA Data Signing using a .pem cert


(Scott Becker) #1

I have a data file: data.txt

I run the following:

rsa_genkey
creates: rsa_priv.txt and rsa_pub.txt as expected

rsa_sign data.txt
creates: data.txt.sig as expected, using rsa_priv.txt

rsa_verify data.txt
verifies data.txt and data.txt.sig using rsa_pub.txt as expected

I need to sign data with a private key using mbedtls in my app and send the data and sig
to a server for verification with the public key using php’s openssl_verify.
(The data and sig will be sent over an https connection.)

So I created a key pair using:
openssl genpkey -algorithm RSA -out private_key.pem -pkeyopt rsa_keygen_bits:2048

I extracted the public key using:
openssl rsa -pubout -in private_key.pem -out public_key.pem

Now I need a utility based on rsa_sign.c which will read private_key.pem and sign
data.

I’ve found: mbedtls_x509_crt_parse so I can read the pem to a buffer and load
it into a mbedtls_x509_crt structure.

I can not find how to create an mbedtls_rsa_context structure from the
mbedtls_x509_crt structure so I can use it to sign the data.

I’ve been programming for almost 30 years but I’m new to Cryptography.
If the certificate I generated is even the right one for rsa signing I’m not
even sure of.

I need a code sample and at what point in rsa_sign.c my new structure
(based on the .pem cert) is useful.

Thanks in advance.
ScottB


(Ron Eldor) #2

@scottb89 thank you for your question!

Note that private_key.pem is not a x509 certificate, but a private key, encoded in PEM format.
I believe a better example for you to follow would be pk_sign.
This example loads a private key, parses it and signs the data. It uses SHA256 as the MD algorithm, bu you can modify it. It uses the pk wrapper code instead of directly using the rsa module. Since you are in need of parsing your key, it is better you use the pk module, that supports parsing the key files as well.
The key_app example will show you how to use the mbedtls_rsa_context within the mbedtls_pk_context holding the key information.

If you have security restrictions, I suggest you consult your security experts about what key size and MD algorithm you need to use.
Regards,
Mbed TLS Team member
Ron