1 /* Certificate creation. Demonstrates some certificate related
9 #include <openssl/pem.h>
10 #include <openssl/conf.h>
11 #include <openssl/x509v3.h>
12 #include <openssl/engine.h>
14 int mkcert(X509 **x509p, EVP_PKEY **pkeyp, int bits, int serial, int days);
15 int add_ext(X509 *cert, int nid, char *value);
17 int main(int argc, char **argv)
23 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
25 bio_err=BIO_new_fp(stderr, BIO_NOCLOSE);
27 mkcert(&x509,&pkey,512,0,365);
29 RSA_print_fp(stdout,pkey->pkey.rsa,0);
30 X509_print_fp(stdout,x509);
32 PEM_write_PrivateKey(stdout,pkey,NULL,NULL,0,NULL, NULL);
33 PEM_write_X509(stdout,x509);
39 CRYPTO_cleanup_all_ex_data();
41 CRYPTO_mem_leaks(bio_err);
46 static void callback(int p, int n, void *arg)
57 int mkcert(X509 **x509p, EVP_PKEY **pkeyp, int bits, int serial, int days)
64 if ((pkeyp == NULL) || (*pkeyp == NULL))
66 if ((pk=EVP_PKEY_new()) == NULL)
75 if ((x509p == NULL) || (*x509p == NULL))
77 if ((x=X509_new()) == NULL)
83 rsa=RSA_generate_key(bits,RSA_F4,callback,NULL);
84 if (!EVP_PKEY_assign_RSA(pk,rsa))
91 X509_set_version(x,3);
92 ASN1_INTEGER_set(X509_get_serialNumber(x),serial);
93 X509_gmtime_adj(X509_get_notBefore(x),0);
94 X509_gmtime_adj(X509_get_notAfter(x),(long)60*60*24*days);
95 X509_set_pubkey(x,pk);
97 name=X509_get_subject_name(x);
99 /* This function creates and adds the entry, working out the
100 * correct string type and performing checks on its length.
101 * Normally we'd check the return value for errors...
103 X509_NAME_add_entry_by_txt(name,"C",
104 MBSTRING_ASC, "UK", -1, -1, 0);
105 X509_NAME_add_entry_by_txt(name,"CN",
106 MBSTRING_ASC, "OpenSSL Group", -1, -1, 0);
108 /* Its self signed so set the issuer name to be the same as the
111 X509_set_issuer_name(x,name);
113 /* Add various extensions: standard extensions */
114 add_ext(x, NID_basic_constraints, "critical,CA:TRUE");
115 add_ext(x, NID_key_usage, "critical,keyCertSign,cRLSign");
117 add_ext(x, NID_subject_key_identifier, "hash");
119 /* Some Netscape specific extensions */
120 add_ext(x, NID_netscape_cert_type, "sslCA");
122 add_ext(x, NID_netscape_comment, "example comment extension");
126 /* Maybe even add our own extension based on existing */
129 nid = OBJ_create("1.2.3.4", "MyAlias", "My Test Alias Extension");
130 X509V3_EXT_add_alias(nid, NID_netscape_comment);
131 add_ext(x, nid, "example comment alias");
135 if (!X509_sign(x,pk,EVP_md5()))
145 /* Add extension using V3 code: we can set the config file as NULL
146 * because we wont reference any other sections.
149 int add_ext(X509 *cert, int nid, char *value)
153 /* This sets the 'context' of the extensions. */
154 /* No configuration database */
155 X509V3_set_ctx_nodb(&ctx);
156 /* Issuer and subject certs: both the target since it is self signed,
157 * no request and no CRL
159 X509V3_set_ctx(&ctx, cert, cert, NULL, NULL, 0);
160 ex = X509V3_EXT_conf_nid(NULL, &ctx, nid, value);
164 X509_add_ext(cert,ex,-1);
165 X509_EXTENSION_free(ex);