OpenSSL: RSA Encryption / Decryption, Key Generation, and Key Preservation

I am trying to create a p2p application that requires the following using RSA in OpenSSL:

-Encryption -Decryption -Generating Keys (done) -Saving and loading keys (done) -Saving the PUBLIC key as bytes so it can be sent over the sockets -Loading keys from the above format 

I decided to use EVP features, whatever that means. However, I find it with great difficulty what functions I need to use to do these things and in what order. The official OpenSSL documentation seems to be nonexistent.

Does anyone know which functions I need to use in which order and in their prototypes? Any example code lying around would also be nice.

Thank you very much in advance,

twitchliquid64.

PS: This is what I still have

 #include <string.h> #include <stdio.h> #include <stdlib.h> #include <openssl/rsa.h> #include <openssl/evp.h> #include <openssl/objects.h> #include <openssl/x509.h> #include <openssl/err.h> #include <openssl/pem.h> #include <openssl/ssl.h> #include <openssl/engine.h> #include <openssl/rand.h> RSA* Generate_KeyPair(void) { char rand_buff[16]; EVP_PKEY *pkey = NULL; RSA* r; char* pass = "passgdfgf";//for now int bits = 512; // 512, 1024, 2048, 4096 unsigned long exp = RSA_F4; // RSA_3 OpenSSL_add_all_algorithms(); RAND_seed(rand_buff, 16); //On linux: RAND_load_file("/dev/urandom", 1024); r = RSA_generate_key(bits,exp,NULL,NULL); if (RSA_check_key(r)!=1);;; //Check key - error out //Create EVP to save to file. pkey = EVP_PKEY_new(); EVP_PKEY_assign_RSA(pkey, r); //Save private key FILE* fp = fopen("private.key", "w"); PEM_write_PrivateKey(fp,pkey,EVP_aes_256_cbc(),NULL,0,NULL,pass) fclose(fp); //Save public key fp = fopen("public.key", "w"); PEM_write_PUBKEY(fp, pkey); fclose(fp); return r; } EVP_PKEY* ReadPrivKey_FromFile(char* filename, char* pass) { FILE* fp = fopen(filename, "r"); EVP_PKEY* key = NULL; PEM_read_PrivateKey(fp, &key, NULL, pass); fclose(fp); return key; } EVP_PKEY* ReadPubKey_FromFile(char* filename) { FILE* fp = fopen(filename, "r"); EVP_PKEY* key = NULL; PEM_read_PUBKEY(fp, &key, NULL, NULL); fclose(fp); return key; } 
+7
source share
1 answer

As said in a comment on my question:

You will find sample code that comes with OpenSSL more useful than documentation. For example, documentation on RSA encryption is displayed in /rsa.c applications. This can help develop OpenSSL command lines to execute each function that you want to use using the command line tool, and then figure out what the code actually does (by checking it) so that you can make the code similar. - David Schwartz

This sample code was exactly what I needed, I advise everyone with a similar problem to consult with the rsa code and header file, as well as their examples of use in the documentation as well.

+7
source

Source: https://habr.com/ru/post/916810/


All Articles