2

I'm trying to write C code of RSA encryption and decryption using Open SSL. But I am not able to do so. I googled it but whatever code I got from internet it was out of my head. main function goes here which I got from stack overflow. I tried using it … but its not working. May be my bad.

encrypt(FILE *rsa_Pkey_fole,FILE *in_file,FILE *out_file){

}

int main(int argc, char *argv[])
{
    FILE *rsa_pkey_file, *infile;
    int rv;

    if (argc < 2) {
            fprintf(stderr, "Usage: %s <PEM RSA Public Key File>\n", argv[0]);
            exit(1);
    }

    rsa_pkey_file = fopen(argv[1], "rb");
    infile = fopen(argv[2], "w");
    if (!rsa_pkey_file) {
        perror(argv[1]);
        fprintf(stderr, "Error loading PEM RSA Public Key File.\n");
        exit(2);
    }

    rv = encrypt(rsa_pkey_file, infile.txt, stdout);
    fclose(rsa_pkey_file);

    return rv;
}

And similar way decryption.

How can I do RSA encryption and decryption of a file using Open SSL library in C in simple way?

6
  • 2
    "it's not working" isn't a particularly useful problem description. catb.org/esr/faqs/smart-questions.html Commented Mar 27, 2013 at 6:13
  • Please post the function encrypt, this main() won't tell us much... Commented Mar 27, 2013 at 6:20
  • sure.. i ll post the encryption part.. its little big.. and i m not able to understand.. Commented Mar 27, 2013 at 7:20
  • @sakshi Could you please at least try to use proper english? This is not 4chan. Commented Mar 27, 2013 at 8:58
  • 1
    @ FUZxxl hope my question is in human readable format.. so if possible try to answer :) Commented Mar 27, 2013 at 9:49

1 Answer 1

4

Steps for RSA encryption are as follows:

  1. Read the public key into RSA * structure. It depends on your key format. If key is in PEM format, use PEM_read_RSA_PUBKEY functions. If it is in DER form, use d2i_RSA.
  2. Encrypt your data using RSA public key. Use RSA_public_encrypt function.
  3. Write the data to file or whatever you want to do.

Steps for RSA decryption are:

  1. Read the private key into RSA * structure. It is similar to step 1 in RSA encryption with some minor difference.
  2. Decrypt the data using RSA_private_decrypt. Use RSA_private_decrypt.

You can look OpenSSL documentation which is quite useful and its names are intuitive. I give you just broad level idea. If you need more help, I can post the code example.

Sign up to request clarification or add additional context in comments.

1 Comment

the man page for RSA_public_encrypt says you need to seed the RNG before calling, implying you need to get some random data from somewhere to pass to RAND_seed...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.