?
Solved

OpenSSL RSA Cryptography.

Posted on 2005-05-11
7
Medium Priority
?
4,142 Views
Last Modified: 2007-12-19
Topic: OpenSSL RSA cryptography.
Platform : MS VC++ 6
               Win32
              OpenSSL


Hello,
I'm working on a project where I must use RSA cryptography.  I'm having a problem getting this simple code shown below work. I think something is wrong with the RSA object. The reason I think so is that each time a function (such as RSA_size() or RSA_public_encrypt()) using the RSA object is encountered I get a run time error. Note that the files holding both public and private keys were generated using the OpenSSL command line tool.
If someone can show me how I can encrypt/decrypt strings or character, numbers and keys as well I'd highly appreciate it. Thanks for your help in advance.

***************************************************************
#include <winsock2.h>
#include <iostream.h>
#include <openssl/rand.h>
#include <openssl/rsa.h>
#include <openssl/engine.h>
#include <openssl/pem.h>
#include <openssl/rand.h>
#include <time.h>


void seed_prng();


int main()
{      
    char *message ="Test Message";            
      RSA            *apub;
      RSA            *aprivate;
      FILE *f;
      int ret;
      unsigned char *buf;
      unsigned char *e_data;
      unsigned char *last_data;
      
      seed_prng();
      printf("\nPRNG seeded\n");
      
      printf("\n Message contents: %s\n", message);

      //Allocating RSA object
                apub = RSA_new();
      if(apub == NULL)
            printf("\n Error creating RSA ojbect public");
      else
            printf("\n Successful alocation of public RSA object");

      aprivate = RSA_new();
      if(aprivate == NULL)
            printf("\n Error creating RSA ojbect private");
      else
            printf("\n Successful alocation of private RSA object");

      //printf("\n Size of RSA is %d", RSA_size(apub));   This generates a runtime error

      //Get key
      f= fopen("a_rsa_public","r");
      if(f == NULL)
      {
            printf("\nError opening public key file");
            return -1;
      }
      else
            printf("\n Public key file opened");

      //load the key
              
      //apub = PEM_read_RSAPublicKey(f, &apub,0 ,0);
      //apub = PEM_read_RSAPublicKey(f, NULL ,NULL ,NULL);
      apub = PEM_read_RSA_PUBKEY(f, NULL, NULL, NULL);
      if (apub == NULL)
      {
            printf("\n Unable to read public file\n");
            return -1;
      }

      //close the key file
      fclose(f);

      
      
    buf = (unsigned char *) malloc(strlen(message)+1);      
      memcpy(buf,message,strlen(message));
      
      e_data = (unsigned char *) malloc(RSA_size(apub));
      //encrypt data

      RSA_public_encrypt(strlen(message)+1,buf, e_data, apub, RSA_PKCS1_OAEP_PADDING);
            
      //------------------decrypt!!
      //Get key
      f= fopen("a_rsa_private","rb");
      if(f == NULL)
      {
            printf("\nError opening private key file");
            return -1;
      }

      //load the key
                aprivate = PEM_read_RSA_PUBKEY(f, NULL, NULL, NULL);
      if (aprivate== NULL)
      {
            printf("\n Unable to read privatefile\n");
            return -1;
      }

      //close the key file
      fclose(f);

            
      last_data = (unsigned char *) malloc(strlen(message));
      RSA_private_decrypt(strlen((char*)e_data), e_data, last_data, aprivate, RSA_PKCS1_OAEP_PADDING);

      RSA_free(apub);
      RSA_free(aprivate);
      return 0;
}



void seed_prng()
{
      time_t rawtime;
      struct tm* timeinfo;

      time(&rawtime);
      timeinfo = localtime(&rawtime);
      RAND_seed(asctime(timeinfo), 4);
}

********************************************************************************
0
Comment
Question by:Layla_2401
7 Comments
 
LVL 12

Expert Comment

by:kneH
ID: 13984255
I'm completely clueless

But I do suggest posting a pointer to this question in the programming forum :)
0
 

Author Comment

by:Layla_2401
ID: 13984784
I already have! but still no answer!
0
 

Author Comment

by:Layla_2401
ID: 13984786
But do I take it that the code is correct?
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 6

Expert Comment

by:alextr2003fr
ID: 15761863
The openssl project includes a sample file to show how to manipulate rsa functions
it can be found in the directory \crypto\rsa\rsatest.c

Hope this helps
0
 
LVL 6

Accepted Solution

by:
alextr2003fr earned 2000 total points
ID: 15761890
About the code
You only need one 'RSA' not 2
RSA          *apub;
RSA          *aprivate;

because it stores both in one : public and private keys
0
 

Author Comment

by:Layla_2401
ID: 15763979
Hi there,

First of all I would like to thank you for taking the time to provide me with a solution even after this considerable amount of time. I have already graduated and I no longer work with OpenSSL. But due to my interest I would still love to get an RSA protocol to run. As I don't currently have time to try either of your suggestions I will go ahead and accept your answer anyway and try it later in my own time, after all its the thought that counts ;)
0
 

Expert Comment

by:tebalusions
ID: 31120566
Hi  am also now tring to write a program in c++ using openssl for RSA encryption an decryption.
I have created teh public key and private key with the openssl commands and saved them in the directory where the c-file is saved.
I am very new to c++ (having no experience with that  - just lil bit java programing knowledge thats all).
Because opening the pem file not succeeded i converted the pem files to txt files.

While loading te key with PEM_read_RSAPublicKey the system crashes.

I urgently need a solution. I am working on windows7. So maybe some settings ahs to be done.
I am trying to find out a solution for days but coul not find any solution.
please if someone can help me - i would be very thankful for that.

thats my code:

#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
#include <io.h>
#include <time.h>
#include <windows.h>


#include <openssl/rand.h>
#include <openssl/rsa.h>
#include <openssl/engine.h>
#include <openssl/pem.h>
#include <openssl/err.h>


int main()
{
      char *message ="Test Message";

      RSA *apub;
      RSA *aprivate;
      FILE *f;


      //******************************************************************************
      //ALLOCATION OF RSA OBJECTS - STARTS HERE
      //******************************************************************************
      apub= RSA_new();
      aprivate= RSA_new();

      if ( apub == NULL)
      {
            printf("\nError creating public RSA object.");
            return -1;
      }
      else
            printf("\nPublic RSA object successfully allocated.");

      if ( aprivate == NULL)
      {
            printf("\nError creating private RSA object.");
            return -1;
      }
      else
            printf("\nPrivate RSA object successfully allocated.");
      //******************************************************************************
      //ALLOCATION OF RSA OBJECTS ENDS HERE
      //******************************************************************************
      printf("\n********************************************");


      //GET PUBLIC KEY WHICH HAS BEEN CREATED WITH OPENSSL COMMANDS - Note pem file converted to txt
      f= fopen("a_rsa_public.txt","rb");
      if(f == NULL)
      {
            printf("\nError opening public key file");
            return -1;
      }
      else
            printf("\nPublic key file opened");


      //******************************************************************************
      //LOADING THE PUBLIC KEY
      //******************************************************************************
      apub = PEM_read_RSA_PUBKEY(f, NULL, NULL,NULL);
      if (apub == NULL)
      {
            printf("\nError reading public key");
            return -1;
      }
      else
            printf("\nPublic key read");

      fclose(f);
      printf("RSA size: %d", RSA_size(apub));


      printf("\n********************************************");

      unsigned char *buf = (unsigned char *) malloc(strlen(message)+1);
      unsigned char *encryptedString = (unsigned char *)malloc(RSA_size(apub));


      //******************************************************************************
      //ENCRYPTION AND VERIFICATION & TIME MEASUREMENT- STARTS HERE
      //******************************************************************************
      SYSTEMTIME now;
      SYSTEMTIME now2;

      GetSystemTime(&now);

      //int i = 5000;
      //while (i > 0)
      //{
            RSA_public_encrypt(strlen(message)+1,buf, encryptedString, apub, RSA_PKCS1_OAEP_PADDING);
            //i=i-1;
      //}

      GetSystemTime(&now2);

      if (RSA_public_encrypt(strlen(message)+1,buf, encryptedString, apub, RSA_PKCS1_OAEP_PADDING) == -1)
            {
                  printf("\nEncryption error");
                  return -1;
            }
            else
                  printf("\nEncryption was successfull");

      printf("Startime of encryption: %02d:%02d:%02d.%03d\n",now.wHour, now.wMinute, now.wSecond, now.wMilliseconds);
      printf("Endtime of encryption: %02d:%02d:%02d.%03d\n",now2.wHour, now2.wMinute, now2.wSecond, now2.wMilliseconds);

      // in case loop has been used duration time has to be divided with the number of loop execution
      printf("Duration of encryption: %02d:%02d:%02d.%03d\n",now2.wHour-now.wHour, now2.wMinute-now.wMinute, now2.wSecond-now.wSecond, now2.wMilliseconds-now.wMilliseconds);
      //******************************************************************************
      //ENCRYPTION AND VERIFICATION - ENDS HERE
      //******************************************************************************


      printf("\n********************************************");

      //GET PRIVATE KEY WHICH HAS BEEN CREATED WITH OPENSSL COMMANDS - Note pem file converted to txt
      f= fopen("a_rsa_private.txt","rb");
      if(f == NULL)
      {
            printf("\nError opening private key file");
            return -1;
      }
      else
            printf("\nPrivate key file opened");


      //******************************************************************************
      //LOADING THE PPRIVATE KEY
      //******************************************************************************
      aprivate = PEM_read_RSAPrivateKey(f, NULL, NULL,NULL);
      if (aprivate == NULL)
      {
            printf("\nError reading private key");
            return -1;
      }
      else
            printf("\nPrivate key read");

      fclose(f);
      printf("RSA size: %d", RSA_size(aprivate));


      printf("\n********************************************");

      unsigned char *plain_text= (unsigned char *) malloc(strlen(message));

      //******************************************************************************
      //DECRYPTION AND VERIFICATION & TIME MEASUREMENT- STARTS HERE
      //******************************************************************************
      SYSTEMTIME now3;
      SYSTEMTIME now4;

      GetSystemTime(&now3);

      //int i = 5000;
      //while (i > 0)
      //{
      RSA_private_decrypt(strlen((char*)encryptedString), encryptedString, plain_text, aprivate, RSA_PKCS1_OAEP_PADDING);
      //i=i-1;
      //}

      GetSystemTime(&now4);

      if (RSA_private_decrypt(strlen((char*)encryptedString), encryptedString, plain_text, aprivate, RSA_PKCS1_OAEP_PADDING) == -1)
      {
                  printf("\nDecryption error");
                  return -1;
      }
      else
                  printf("\nDecryption was successfull");

      printf("Startime of encryption: %02d:%02d:%02d.%03d\n",now3.wHour, now3.wMinute, now3.wSecond, now3.wMilliseconds);
      printf("Endtime of encryption: %02d:%02d:%02d.%03d\n",now4.wHour, now4.wMinute, now4.wSecond, now4.wMilliseconds);

      // in case loop has been used duration time has to be divided with the number of loop execution
      printf("Duration of decryption: %02d:%02d:%02d.%03d\n",now4.wHour-now3.wHour, now4.wMinute-now3.wMinute, now4.wSecond-now3.wSecond, now4.wMilliseconds-now3.wMilliseconds);


      //******************************************************************************
      //DECRYPTION AND VERIFICATION - ENDS HERE
      //******************************************************************************
      RSA_free(apub);
      RSA_free(aprivate);

}
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

With the evolution of technology, we have finally reached a point where it is possible to have home automation features like having your thermostat turn up and door lock itself when you leave, as well as a complete home security system. This is a st…
Considering today’s continual security threats, which affect Information technology networks and systems worldwide, it is very important to practice basic security awareness. A normal system user can secure himself or herself by following these simp…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…
Suggested Courses

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question