7.6. Generating an RSA Key Pair

Problem

You want to use RSA to encrypt data, and you need to generate a public key and its corresponding private key.

Solution

Use a cryptography library’s built-in functionality to generate an RSA key pair. Here we’ll describe the OpenSSL API. If you insist on implementing RSA yourself (generally a bad idea), see the following discussion.

Discussion

Tip

Be sure to see Recipe 7.1 and Recipe 7.2 for general-purpose guidance on using public key cryptography.

The OpenSSL library provides a function, RSA_generate_key( ) , that generates a {public key, private key} pair, which is stored in an RSA object. The signature for this function is:

RSA *RSA_generate_key(int bits, unsigned long exp, void (*cb)(int, int, void), 
                      void *cb_arg);

This function has the following arguments:

bits

Size of the key to be generated, in bits. This must be a multiple of 16, and at a bare minimum it should be at least 1,024. 2,048 is a common value, and 4,096 is used occasionally. The more bits in the number, the more secure and the slower operations will be. We recommend 2,048 bits for general-purpose use.

exp

Fixed exponent to be used with the key pair. This value is typically 3, 17, or 65,537, and it can vary depending on the exact context in which you’re using RSA. For example, public key certificates encode the public exponent within them, and it is almost universally one of these three values. These numbers are common because it’s fast to multiply other numbers with these numbers, ...

Get Secure Programming Cookbook for C and C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.