1 /* Certificate request creation. Demonstrates some request related
8 #include <openssl/pem.h>
9 #include <openssl/conf.h>
10 #include <openssl/x509v3.h>
11 #include <openssl/engine.h>
13 int mkreq(X509_REQ **x509p, EVP_PKEY **pkeyp, int bits, int serial, int days);
14 int add_ext(STACK_OF(X509_REQUEST) *sk, int nid, char *value);
16 int main(int argc, char **argv)
22 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
24 bio_err=BIO_new_fp(stderr, BIO_NOCLOSE);
26 mkreq(&req,&pkey,512,0,365);
28 RSA_print_fp(stdout,pkey->pkey.rsa,0);
29 X509_REQ_print_fp(stdout,req);
31 PEM_write_X509_REQ(stdout,req);
37 CRYPTO_cleanup_all_ex_data();
39 CRYPTO_mem_leaks(bio_err);
44 static void callback(int p, int n, void *arg)
55 int mkreq(X509_REQ **req, EVP_PKEY **pkeyp, int bits, int serial, int days)
61 STACK_OF(X509_EXTENSION) *exts = NULL;
63 if ((pk=EVP_PKEY_new()) == NULL)
66 if ((x=X509_REQ_new()) == NULL)
69 rsa=RSA_generate_key(bits,RSA_F4,callback,NULL);
70 if (!EVP_PKEY_assign_RSA(pk,rsa))
75 X509_REQ_set_pubkey(x,pk);
77 name=X509_REQ_get_subject_name(x);
79 /* This function creates and adds the entry, working out the
80 * correct string type and performing checks on its length.
81 * Normally we'd check the return value for errors...
83 X509_NAME_add_entry_by_txt(name,"C",
84 MBSTRING_ASC, "UK", -1, -1, 0);
85 X509_NAME_add_entry_by_txt(name,"CN",
86 MBSTRING_ASC, "OpenSSL Group", -1, -1, 0);
88 #ifdef REQUEST_EXTENSIONS
89 /* Certificate requests can contain extensions, which can be used
90 * to indicate the extensions the requestor would like added to
91 * their certificate. CAs might ignore them however or even choke
92 * if they are present.
95 /* For request extensions they are all packed in a single attribute.
96 * We save them in a STACK and add them all at once later...
99 exts = sk_X509_EXTENSION_new_null();
100 /* Standard extenions */
102 add_ext(exts, NID_key_usage, "critical,digitalSignature,keyEncipherment");
104 /* This is a typical use for request extensions: requesting a value for
105 * subject alternative name.
108 add_ext(exts, NID_subject_alt_name, "email:steve@openssl.org");
110 /* Some Netscape specific extensions */
111 add_ext(exts, NID_netscape_cert_type, "client,email");
116 /* Maybe even add our own extension based on existing */
119 nid = OBJ_create("1.2.3.4", "MyAlias", "My Test Alias Extension");
120 X509V3_EXT_add_alias(nid, NID_netscape_comment);
121 add_ext(x, nid, "example comment alias");
125 /* Now we've created the extensions we add them to the request */
127 X509_REQ_add_extensions(x, exts);
129 sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
133 if (!X509_REQ_sign(x,pk,EVP_md5()))
143 /* Add extension using V3 code: we can set the config file as NULL
144 * because we wont reference any other sections.
147 int add_ext(STACK_OF(X509_REQUEST) *sk, int nid, char *value)
150 ex = X509V3_EXT_conf_nid(NULL, NULL, nid, value);
153 sk_X509_EXTENSION_push(sk, ex);