RSA_public_encrypt() -- SSLeay 0.9.0b -- January 1999

NAME

RSA_new, RSA_free, RSA_size, RSA_public_encrypt, RSA_private_encrypt,
RSA_public_decrypt, RSA_private_decrypt, RSA_generate_key, RSA_sign,
RSA_verify, RSA_new_method, RSA_flags, RSA_set_default_method,
RSA_PKCS1_RSAref, ERR_load_RSA_strings, d2i_RSAPublicKey, i2d_RSAPublicKey,
d2i_RSAPrivateKey, i2d_RSAPrivateKey, RSA_print_fp, RSA_print,
i2d_Netscape_RSA, d2i_Netscape_RSA, d2i_Netscape_RSA_2,
RSA_sign_ASN1_OCTET_STRING, RSA_verify_ASN1_OCTET_STRING, RSA_blinding_on,
RSA_blinding_off, RSA_padding_add_PKCS1_type_1,
RSA_padding_check_PKCS1_type_1, RSA_padding_add_PKCS1_type_2,
RSA_padding_check_PKCS1_type_2, RSA_padding_add_SSLv23,
RSA_padding_check_SSLv23, RSA_padding_add_none, RSA_padding_check_none,
RSA_get_ex_new_index, RSA_set_ex_data, RSA_get_ex_data -- RSA encryption

SYNOPSIS

#include "rsa.h"

RSA *RSA_new();

void RSA_free(rsa)
RSA *rsa;

int RSA_size(rsa)
RSA *rsa;

int RSA_public_encrypt(from_len, from, to, rsa)
int from_len;
unsigned char *from, *to;
RSA *rsa;

int RSA_private_encrypt(flen, from, to, rsa)
int from_len;
unsigned char *from, *to;
RSA *rsa;

int RSA_public_decrypt(flen, from, to, rsa)
int from_len;
unsigned char *from, *to;
RSA *rsa;

int RSA_private_decrypt(flen, from, to, rsa)
int from_len;
unsigned char *from, *to;
RSA *rsa;

RSA *RSA_generate_key(bits, e, callback, cb_arg)
int bits;
unsigned long e;
void (*callback)();
char *cb_arg;

int RSA_sign(type, m, m_len, sigret, siglen, rsa)
int type;
unsigned char *m, *sigret;
unsigned int m_len, *siglen;
RSA *rsa;

int RSA_verify(type, m, m_len, sigbuf, siglen, rsa)
int type;
unsigned char *m, *sigbuf;
unsigned int m_len, siglen;
RSA *rsa;

int RSA_sign_ASN1_OCTET_STRING(type, m, m_len, sigret, siglen, rsa)
int type;
unsigned char *m, *sigret;
unsigned int m_len, *siglen;
RSA *rsa;

int RSA_verify_ASN1_OCTET_STRING(type, m, m_len. sigbuf, siglen, rsa)
int type;
unsigned char *m, *sigbuf;
unsigned int m_len, siglen;
RSA *rsa;

int RSA_flags(r)
RSA *r;

void RSA_set_default_method(meth)
RSA_METHOD *meth;

/* If you have RSAref compiled in. */ RSA_METHOD *RSA_PKCS1_RSAref();

/* these are the actual SSLeay RSA functions */ RSA_METHOD *RSA_PKCS1_SSLeay();

void ERR_load_RSA_strings();

int RSA_print_fp(fp, r, offset)
FILE *fp;
RSA *r;
int offset;

int RSA_print(bp, r, offset)
BIO *bp;
RSA *r;
nt offset;

RSA *d2i_RSAPublicKey(a, pp, length)
RSA **a;
unsigned char **pp;
long length;

int i2d_RSAPublicKey(a, pp)
RSA *a;
unsigned char **pp;

RSA *d2i_RSAPrivateKey(a, pp, length)
RSA **a;
unsigned char **pp;
long length;

int i2d_RSAPrivateKey(a, pp)
RSA *a;
unsigned char **pp;

int i2d_Netscape_RSA(a, pp, cb)
RSA *a;
unsigned char **pp;
int (*cb)();

RSA *d2i_Netscape_RSA(a, pp, length, cb)
RSA **a;
unsigned char **pp;
long length;
int (*cb)();

RSA *d2i_Netscape_RSA_2(a, pp, length, cb)
RSA **a;
unsigned char **pp;
long length;
int (*cb)();

int RSA_blinding_on(rsa, ctx)
RSA *rsa;
BN_CTX *ctx;

void RSA_blinding_off(rsa)
RSA *rsa;

int RSA_padding_add_PKCS1_type_1(to, tlen, f, fl)
unsigned char *to, *f;
int tlen, fl;

int RSA_padding_check_PKCS1_type_1(to, tlen, f, fl)
unsigned char *to, *f;
int tlen, fl;

int RSA_padding_add_PKCS1_type_2(to, tlen, f, fl)
unsigned char *to, *f;
int tlen, fl;

int RSA_padding_check_PKCS1_type_2(to, tlen, f, fl)
unsigned char *to, *f;
int tlen, fl;

int RSA_padding_add_SSLv23(to, tlen, f, fl)
unsigned char *to, *f;
int tlen, fl;

int RSA_padding_check_SSLv23(to, tlen, f, fl)
unsigned char *to, *f;
int tlen, fl;

int RSA_padding_add_none(to, tlen, f, fl)
unsigned char *to, *f;
int tlen, fl;

int RSA_padding_check_none(to, tlen, f, fl)
unsigned char *to, *f;
int tlen, fl;

int RSA_get_ex_new_index(argl, argp, new_func, dup_func, free_func)
long argl;
char *argp;
int (*new_func)();
int (*dup_func)();
void (*free_func)();

int RSA_set_ex_data(r, idx, arg)
RSA *r;
int idx;
char *arg;

char *RSA_get_ex_data(r, idx)
RSA *r;
int idx;

DESCRIPTION

The RSA routines all refer to the RSA structure which contains:

typedef struct rsa_st
        {
        /* The first parameter is used to pick up errors where
         * this is passed instead of an EVP_PKEY; then it is set to 0 */
        int pad;
        int version;
        RSA_METHOD *meth;
        BIGNUM *n;
        BIGNUM *e; /* public */
        BIGNUM *d; /* private */
        BIGNUM *p;
        BIGNUM *q;
        BIGNUM *dmp1;  /* d mod p */
        BIGNUM *dmq1;  /* d mod q */
        BIGNUM *iqmp;  /* q^-1 mod p */
        /* be careful using this if the RSA structure is shared */
        char *app_data;
        int references;
        int flags;

        /* Normally used to cached montgomery values */
        char *method_mod_n;
        char *method_mod_p;
        char *method_mod_q;

        BN_BLINDING *blinding;
        } RSA;

As you can see from the structure, both the public key and the private key may be stored in this structure. (Depending on how the structure is used, some fields may be NULL; for example, if a public key is loaded into this structure, naturally e will be NULL.) There is no limit on the size of n, save disk space, memory, and your patience while you wait for encryption/decryption.

See the BIGNUM (BN) library for details of the multiprecision elements in the structure.

The RSA_METHOD is defined as follows:

typedef struct rsa_meth_st
        {
        char *name;
        int (*rsa_pub_enc)();
        int (*rsa_pub_dec)();
        int (*rsa_priv_enc)();
        int (*rsa_priv_dec)();
        int (*rsa_mod_exp)();
        int (*bn_mod_exp)();
        int (*init)(/* RSA * */);       /* called at new */
        int (*finish)(/* RSA * */);     /* called at free */

        int flags;                      /* RSA_METHOD_FLAG_* things */
        char *app_data;                 /* may be needed! */
        } RSA_METHOD;

and there is only one method defined at present, namely:

static RSA_METHOD rsa_pkcs1_eay_meth={
        "Eric Young's PKCS#1 RSA",
        RSA_eay_public_encrypt,
        RSA_eay_public_decrypt,
        RSA_eay_private_encrypt,
        RSA_eay_private_decrypt,
        RSA_eay_mod_exp,
        BN_mod_exp_mont,
        RSA_eay_init,
        RSA_eay_finish,
        0,
        NULL,
        };
You get a pointer to this by calling RSA_PKCS1_SSLeay().

Actually, that is a lie; there is also the method you get when you compile against RSAref; you get that method by calling RSA_PKCS1_RSAref().

All RSA encryption is done according to the PKCS#1 standard which is compatible with PEM and RSAref. This means that any value being encrypted must be less than the size of the modulus in bytes, minus 10, bytes long.

This library uses RAND_bytes()() for its random data. Make sure to feed RAND_seed() with lots of interesting and varied data before using these routines.

There are support routines in the X509 library for loading and manipulating the various objects in the RSA library. See the ERR library for details about error handling.

RSA_new() creates a new RSA object, with the BIGNUM subfields set to NULL, and the meth element of the structure set to default_RSA_meth, a static pointer which you can set yourself by calling RSA_set_default_method; see below for details. If default_RSA_meth is NULL, the meth element of the structure will be set to RSA_PKCS1_RSAref if you have RSAref defined, or to rsa_pkcs1_eay_meth otherwise.

RSA_free() frees an RSA structure and any allocated subfields (such as the BIGNUM elements); the BIGNUM members are set to zero before being freed.

RSA_size() returns the size of the RSA modulus in bytes. Use this to determine how long arguments to the various RSA encrypt/decrypt routines (see below).

RSA_public_encrypt(), using the specific rsa_pub_enc function provided by the method specified in the RSA structure, takes from_len bytes from from, performs RSA encryption using the key rsa, and puts the results into to. It is the user's responsibility to provide RSA_size(rsa) bytes in to for storage of the result. Depending on the padding type, you may need to allot an extra 11 bytes. On successful completion, it returns the number of bytes written into to, or -1 on error. To get back plaintext, call RSA_private_decrypt.

RSA_private_encrypt(), using the specific rsa_priv_enc function provided by the method specified in the RSA structure, takes from_len bytes from from, performs RSA encryption using the (private) key rsa, and puts the results into to. It is the user's responsibility to provide RSA_size(rsa) bytes in to for storage of the result. Depending on the padding type, you may need to allot an extra 11 bytes. On successful completion, it returns the number of bytes written into to, or -1 on error. To get back plaintext, call RSA_public_decrypt.

RSA_public_decrypt(), using the specific rsa_pub_dec function provided by the method specified in the RSA structure, takes from_len bytes from from, performs RSA decryption using the key rsa, and puts the results into to. It is the user's responsibility to provide RSA_size(rsa) bytes in to for storage of the result. On successful completion, it returns the number of bytes written into to, or -1 on error.

RSA_private_decrypt(), using the specific rsa_priv_dec function provided by the method specified in the RSA structure, takes from_len bytes from from, performs RSA decryption using the (private) key rsa, and puts the results into to. It is the user's responsibility to provide RSA_size(rsa) bytes in to for storage of the result. On successful completion, it returns the number of bytes written into to, or -1 on error.

RSA_generate_key() is used to generate RSA private keys. It takes quite a period of time to run, since it does prime generation and not just any pair of primes will do. Since it is slow, it should only be used to generate initial private keys that should then be stored for later use. The passed callback function will be called periodically so that feedback can be given to the user as to how this function is progressing. bits is the length in bits desired for the modulus; set this to 1024 to generate a 1024-bit key (for example). e is the value to use for the public exponent 'e'. Traditionally it is set to either 3 or 0x10001.

The callback function (if not NULL) is called in the following situations:

This function returns NULL on error (which usually means malloc ran out of memory).

RSA_sign expects the caller to pass:

the RSA structure containing the key to use for signing, in rsa, the message digest to be signed in m, the length of the message digest in m_len, and the signature algorithm in type, which can be any of the nids associated with a digest algorithm (see the Hashes section for more information). The OID of the algorithm is stuffed in before the data before signing, as per PKCS#1:

DigestInfo ::= SEQUENCE {
  digestAlgorithm DigestAlgorithmIdentifier,
  digest Digest }

First the digest algorithm identifier (type) and the digest are converted to ASN1 der-encoded form using the above definition; then this data is stuffed into an encryption block using PCKS#1-style padding, the whole mess is converted to an integer, encrypted using private key in the RSA structure passed by the user, and finally the results are converted back to an octet-string.

The signature is returned in sig_ret and the length of the signature is returned in sig_len.

This routine is PCKS#1-compliant. See PKCS#1 for more information on PCKS#1.

RSA_sign_ASN1_OCTET_STRING acts just like RSA_sign except that it expects an octet string rather than a message digest. In this case the octet string is converted to ASN1 der-encoded format, and then the rest of the processing proceeds as usual.

type is ignored. (I wonder why it is a parameter?).

RSA_verify expects the caller to pass: the RSA structure containing the key to use for verification, in rsa, sig_len, the length of the signature data, dtype, the NID of the signature algorithm used, m_len, the length of the digest before it was signed, and m, the message digest before it was signed.

The routine uses the public key supplied in the RSA structure to decrypt the signature data and then checks that m, m_len, and dtype as passed by the caller all correspond to the message digest, digest length, and NID of the digest algorithm of the decrypted signature data.

If the NID passed by the user does not match the algorithm identifier actually given in the signed data, (see description of RSA_sign above), but the user's NID is md5 or md2 and the data's algorithm identifier is NID_md5WithRSAEncryption or NID_md2WithRSAEncryption, respectively, this is accepted as valid, but a complaint is logged to stderr.

On successful verification, 1 is returned, else the appropriate error is set for error-handling routines and 0 is returned.

RSA_verify_ASN1_OCTET_STRING functions just like RSA_verify() except that dtype is ignored. I wonder why it is a parameter?

RSA_flags returns the flags element of the RSA structure pointed to by r. Values include: RSA_FLAG_BLINDING, RSA_FLAG_CACHE_PRIVATE, RSA_FLAG_CACHE_PUBLIC, RSA_METHOD_FLAG_NO_CHECK, and RSA_FLAG_THREAD_SAFE.

RSA_FLAG_CACHE_PUBLIC if set will cause caching of the public key for doing montgomery multiplication in the BN routines, if the rsa_pkcs1_eay_meth RSA_METHOD is being used. This occurs during the RSA_public_encrypt routine.

Similarly, RSA_FLAG_CACHE_PRIVATE if set will cause caching of the public key for doing montgomery multiplication in the BN routines, if the rsa_pkcs1_eay_meth RSA_METHOD is being used, and the RSA_private_encrypt routine is called.

RSA_FLAG_BLINDING if set will cause the data to be blinded using BN_BLINDING routines before encryption or decryption of the data is done. The result will then be unblinded. This all holds only if the rsa_pkcs1_eay_meth RSA_METHOD is being used.

At present the other flags are not used.

RSA_set_default_method sets the static variable default_RSA_meth to the supplied meth.

RSA_PKCS1_RSAref is only called when passing it as an argument to RSA_set_default_method (see above). It is available if you have (had to) compile against RSAref.

RSA_PKCS1_SSLeay is only called when passing it as an argument to RSA_set_default_method (see above). It is available if you have NOT had to compile against RSAref.

ERR_load_RSA_strings initializes arrays for the error-handling library with messages specific to the RSA library. Call this before using any RSA routines in your code.

RSA_print is actually defined in the ASN1 library. This function prints out the RSA parameters passed in r to the BIO file specified by bp. The format is fixed and looks like this:

Private-Key: (xx bit) modulus: xxxxxxxxxxx publicExponent: xxxxxxxxxxxxx privateExponent: xxxxxxxxxxxx prime1: xxxxxxxxxxxxxxxx prime2: xxxxxxxxxxxxxxxxx exponent1: xxxxxxxxxxxxxxx exponent2: xxxxxxxxxxxxxxx coefficient: xxxxxxxxxxxxxxx

where the xxx are hex numbers.

offset is used to determine how many leading blanks to put in front of each field. If offset is greater than 128 it is quietly reset to 128 and the new value used instead.

RSA_print_fp is actually defined in the ASN1 library. This function prints out the RSA parameters passed in r to the file specified by fp. It calls RSA_print to do the most of the work.

RSA_blinding_on initializes blinding values in ctx and sets the RSA_FLAG_BLINDING value in rsa->flags. If ctx is NULL a new one will be allocated and used for this purpose.

RSA_blinding_off frees all elements of rsa->blinding and turns off RSA_FLAG_BLINDING in rsa->flags.

RSA_padding_add_*_type_#(to, tlen, f, fl), where * is one of: PKCS1, SSLv23, none and # is one of: 1, 2, adds padding of the specified type to the data in f, with length flen, and puts the result in to, up to tlen bytes. If to is not long enough to contain the result, an error is noted and 0 is returned.

In all of these routines, a type of 1 corresponds to a 'private key block' and a type of 2 corresponds to a 'public key block'. See PKCS#1 for more details.

RSA_padding_check_*_type_#(to, tlen, f, fl), where * is one of: PKCS1, SSLv23, none and # is one of: 1, 2, checks the padding of the specified type in the data in f, with length flen, and puts the data minus the padding in to, up to tlen bytes. If to is not long enough to contain the result, (or equivalently the end of data merker is not reached before to is filled) an error is noted and -1 is returned, as is done if the padding is incorrect for any other reason.

The following routines allow you to set callbacks that are called when an RSA structure using the given RSA method is created, duplicated, or freed. This relies on two static variables, so consider carefully before compiling this for threads and using these routines. The variables are:

int rsa_meth_num=0;

STACK *rsa_meth=NULL;

where rsa_meth points to a stack of CRYPTO_EX_DATA_FUNCS; this structure has the following form:

typedef struct crypto_ex_data_func_st
{
  long argl;      /* Arbitary long */
  char *argp;     /* Arbitary char * */
  /* Called when a new object is created */
  int (*new_func)(/*char *obj,char *item,int index,long argl,char *argp*/);
  /* Called when this object is free()ed */
  void (*free_func)(/*char *obj, char *item,int index,long argl,char *argp*/);
  /* Called when we need to dup this one */
  int (*dup_func)(/*char *obj_to,char *obj_from,
                      char **new,int index,long argl,char *argp*/);
} CRYPTO_EX_DATA_FUNCS;

RSA_get_ex_new_index increments the rsa_meth_num which is just an index into the stack rsa_meth, creates a new stack entry of type pointer to CRYPTO_EX_DATA_FUNCS, stuffs the various fields and functions into the structure, and returns the number of the entry in the stack. If something goes awry, -1 is returned.

The next two routines both rely on the structure CRYPTO_EX_DATA, defines as follows:

typedef struct crypto_ex_data_st
        {
        STACK *sk;
        int dummy; /* gcc is screwing up this data structure :-( */
        } CRYPTO_EX_DATA;

RSA_set_ex_data sets the stack entry with index idx in r->ex_data to point to the value arg, creating NULL entries and pushing them onto r->ex_data first, if necessary.

char *RSA_get_ex_data
retrieves the value of the stack entry in r->ex_data with index b>idx.

Now when your RSA structure is finally freed (for example),

CRYPTO_free_ex_data((rsa_meth,(char *)r,&r->ex_data);

is executed, forcing the appropriate free() function as previously set up in rsa_meth to be invoked on the appropriate data item in the r->ex_data stack.

The other routines are invoked in a similar fashion; look at the file ex_data.c for more details.

The following functions are actually provided by the ASN1 library.

RSA *d2i_RSAPublicKey(RSA **a, unsigned char **pp, long length);
int  i2d_RSAPublicKey(RSA *a, unsigned char **pp);
RSA *d2i_RSAPrivateKey(RSA **a, unsigned char **pp, long length);
int  i2d_RSAPrivateKey(RSA *a, unsigned char **pp);
int  i2d_Netscape_RSA(RSA *a, unsigned char **pp, int (*cb)());
RSA *d2i_Netscape_RSA(RSA **a, unsigned char **pp, long length, int (*cb)());
RSA *d2i_Netscape_RSA_2(RSA **a, unsigned char **pp, long length, int (*cb)());

See ASN.1 conversion to and from DER-encoded form for how to use these i2d and d2i functions.

Note: the Netscape routines convert the private key field of the RSA structure to a Netscape-style private key before doing additional processing.

This key structure contains the following:

typedef struct netscape_pkey_st
        {
        ASN1_INTEGER *version;
        X509_ALGOR *algor;
        ASN1_OCTET_STRING *private_key;
        } NETSCAPE_PKEY;

This is used when you want to write Netscape-format certificates.