xref: /openssl/crypto/x509/x509_r2x.c (revision e077455e)
1 /*
2  * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9 
10 #include <stdio.h>
11 #include "internal/cryptlib.h"
12 #include <openssl/bn.h>
13 #include <openssl/evp.h>
14 #include <openssl/asn1.h>
15 #include <openssl/x509.h>
16 #include "crypto/x509.h"
17 #include <openssl/objects.h>
18 #include <openssl/buffer.h>
19 
X509_REQ_to_X509(X509_REQ * r,int days,EVP_PKEY * pkey)20 X509 *X509_REQ_to_X509(X509_REQ *r, int days, EVP_PKEY *pkey)
21 {
22     X509 *ret = NULL;
23     X509_CINF *xi = NULL;
24     const X509_NAME *xn;
25     EVP_PKEY *pubkey = NULL;
26 
27     if ((ret = X509_new()) == NULL) {
28         ERR_raise(ERR_LIB_X509, ERR_R_ASN1_LIB);
29         return NULL;
30     }
31 
32     /* duplicate the request */
33     xi = &ret->cert_info;
34 
35     if (sk_X509_ATTRIBUTE_num(r->req_info.attributes) != 0) {
36         if ((xi->version = ASN1_INTEGER_new()) == NULL)
37             goto err;
38         if (!ASN1_INTEGER_set(xi->version, 2))
39             goto err;
40 /*-     xi->extensions=ri->attributes; <- bad, should not ever be done
41         ri->attributes=NULL; */
42     }
43 
44     xn = X509_REQ_get_subject_name(r);
45     if (X509_set_subject_name(ret, xn) == 0)
46         goto err;
47     if (X509_set_issuer_name(ret, xn) == 0)
48         goto err;
49 
50     if (X509_gmtime_adj(xi->validity.notBefore, 0) == NULL)
51         goto err;
52     if (X509_gmtime_adj(xi->validity.notAfter, (long)60 * 60 * 24 * days) ==
53         NULL)
54         goto err;
55 
56     pubkey = X509_REQ_get0_pubkey(r);
57     if (pubkey == NULL || !X509_set_pubkey(ret, pubkey))
58         goto err;
59 
60     if (!X509_sign(ret, pkey, EVP_md5()))
61         goto err;
62     return ret;
63 
64  err:
65     X509_free(ret);
66     return NULL;
67 }
68