OpenSSL is a set of widely used open Source code It not only implements SSL, but also provides many useful tools, such as generating RSA key pairs, generating certificate requests, and small ca. We generally use these gadgets through OpenSSL commands. Is there a way to directly call OpenSSL functions to implement these functions? The answer is yes.
Today we will introduce how to use OpenSSL programming to generate an RSA key pair. The simplest way is to use the system call: exec ("OpenSSL RSA-generate ")...... (Countless feet ......) Just make a joke and start with the question.
First, it should be clear that the file structures of openssl0.9.8 and openssl0.9.7 are significantly different. openssl0.9.8 adds several header files and some new interfaces. the header files with the same name as openssl0.9.7 are left, the content has also been changed. To generate an RSA key pair, openssl0.9.8 provides an interface that is completely different from openssl0.9.7:
Int rsa_generate_key_ex (RSA * RSA, int bits, bignum * E, bn_gencb * CB );
The meanings of parameters are as follows:
RSA * RSA: Data Structure pointer for storing the generated key pair, which requires space allocation in advance;
Int bits: the number of bytes of the key pair. Generally, the index of 2 is or;
Bignum * E: RSA key generationAlgorithmMust be initialized in advance; bn_gencb * CB: not clear at the moment ......;
The key is RSA * RSA. The generated key pair is stored here.
The initialization method of each parameter is as follows:
RSA = rsa_new ();
Out = bio_new (bio_s_file ());
(Another version is bio * tmpbio = bio_new (bio_f_linebuffer (); out = bio_push (tmpbio, out); I don't know which one is correct. I look forward to the next experiment)
Bn_gencb * CB; just define a static variable.
Set the BN parameter:
Bn_set_word (bn, 0x10001 );
It can be set to 65537 or 3. The former is used more often.
After setting the preceding parameters, you can generate an RSA key pair. If you use the evp_pkey_assign_rsa () and pem_write_bio_privatekey () interfaces, you can export the private key to a password-encrypted PEM file. These two interfaces are still in the experiment ......
Note that the include directory in the openssl0.9.8 source file is very different from the inc32 directory. The inc32 directory must be used for compiling in windows; otherwise, an error is reported. (I suffered this loss ...... 5555)
By the way, openssl0.9.8 is backward compatible with the key generation interface of openssl0.9.7:
RSA * rsa_generate_key (INT bits, unsigned long e, void & nbsp; (* callback) (INT, Int, void *), void * cb_arg );
Obviously, the new key generation function is more concise.