title: OpenSSL: RSA Encryption/Decryption, key generation & key persistance
body: <p>I am trying to build a p2p application that requires the following, using RSA in OpenSSL:</p>
  
  <pre><code>-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
  </code></pre>
  
  <p>I have chosen to use the EVP functions, whatever that means. However I am having supreme difficulty finding which functions I need to use to do these things, and in what order. Official documentation of OpenSSL seems to be non-existant.</p>
  
  <p>Does anyone know what functions I need to use in what order and their prototypes? Any example code lying around would also be nice.</p>
  
  <p>Thanks much in advance,</p>
  
  <p>twitchliquid64.</p>
  
  <p><strong>PS: This is what I have so far</strong></p>
  
  <pre><code>#include &lt;string.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;openssl/rsa.h&gt;
  #include &lt;openssl/evp.h&gt;
  #include &lt;openssl/objects.h&gt;
  #include &lt;openssl/x509.h&gt;
  #include &lt;openssl/err.h&gt;
  #include &lt;openssl/pem.h&gt;
  #include &lt;openssl/ssl.h&gt;
  #include &lt;openssl/engine.h&gt;
  #include &lt;openssl/rand.h&gt;
  
  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, &amp;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, &amp;key, NULL, NULL);
    fclose(fp);
  
    return key;
  }
  </code></pre>