简体   繁体   中英

How to read/write the public key in an RSA structure

Using C, I can generate and write an RSA public key to a PEM file using PEM_write_RSAPublicKey() ,

But I want to write multiple public keys to a single file (like known_hosts or authorized_hosts), rather than have a separate PEM file for each .

I know how to encode/decode base64 ,

But how do I get the public key from the RSA structure (which I can base64 encode) and later read the same key from file and put it back into the RSA structure for encrypting/decrypting ?

PEM_write_RSAPublicKey() will append to the file if opened with "a+" but there is no indication of which keys are for which client. I don't want PEM formatting, only to write each public key to a single line in the file.

I found that the public key is in DER format, which I can get from the RSA struct using:

len = i2d_RSAPublicKey(rsap, 0);
buf1 = buf2 = (unsigned char *)malloc(len + 1);
rc = i2d_RSAPublicKey(rsap, (unsigned char **)&buf2);

Then I base64-encode buf1 and write it to my file. After reading it from file, putting it back into the RSA struct is just the reverse:

rsap = d2i_RSAPublicKey(NULL, (const unsigned char **)&buf1, (long)len);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM