RSA BSAFE Micro Edition Suite

Streamlined security for mobile and embedded devices

Search  Print

Generating a Self-Signed Certificate

This sample demonstrates how to generate a self-signed certificate from start to finish, without an existing request.

Sample Description:
------------------
This sample shows how to generate a self-signed certificate from 
start to finish, without an existing request.

Procedure:
----------
 1) Create the output BIO.
 2) Create the library context.
 3) Create the public/private key pair for certificate generation.
 4) Create the notBefore/notAfter time for certificate generation.
 5) Create a certificate object.
 6) Set the required information in the certificate object.
 7) Sign the certificate object information with the  private key.
 8) Write out the certificate information into a file.
 9) Clean up.

  

/* $Id: ss_cert_smpl.c,v 1.22 2005/02/07 00:31:30 jmckee Exp $ */
/*
 * Copyright (C) 1998-2003 RSA Security Inc.
 *
 * This file shall only be used to demonstrate how to interface to an
 * RSA Security Inc. licensed development product.
 *
 * You have a royalty-free right to use, reproduce and distribute this
 * demonstration file, provided that you agree that RSA Security Inc.
 * has no warranty, implied or otherwise, or liability for this
 * demonstration file (including any modified version).  This software
 * is provided "as is" without warranties or representations of any
 * kind. RSA Security disclaims all conditions and warranties, statutory
 * and otherwise, both express and implied, with respect to the software,
 * its quality and performance, including but not limited to, all
 * implied warranties of merchantability, fitness for a particular
 * purpose, title and noninfringement of third party rights. Without
 * limiting the foregoing, RSA Security does not warrant that the
 * software is error-free or that errors in the product will be
 * corrected. You agree that RSA Security shall not be liable for any
 * direct, indirect, incidental, special, consequential, punitive or
 * other damages whatsoever resulting from your use of this software
 * or any modified version.
 *
 *
 */

#include "r_prod.h"

#include "r_cert_r.h"
#include "r_pkey_mth.h"



/*
 * Build up a static resource. Only these modules are required for
 * this sample application.
 */
static R_RES_ITEM cert_rl_items[] =
{
    R_CR_RES_CRYPTO_DEFAULT,
    R_CR_RES_SIGNATURE_MAP,
#ifndef NO_BN
    R_TIME_RES_MI,
#else
    R_TIME_RES_UTC,
#endif
    R_PKEY_RES_RSA,
    R_CERT_RES_X509,
    R_LIB_RES_DEFAULT,
    R_RES_END_OF_LIST
};

/*
 * Main sample program entry point.
 *
 * @param argc  [In]  The number of arguments typed on the command line.
 * @param argv  [In]  The array of individual arguments from the command line.
 *
 * @returns  R_ERROR_NONE indicates success.<br>
 *           See @ref R_ERROR_IDS for valid values.
 */
int main(int argc, char **argv)
{
    int ret = R_ERROR_NONE;                              /* The return value */
    BIO *bio_err = NULL;                 /* The standard error output stream */
    BIO *bio_out = NULL;                       /* The standard output stream */
    BIO *bio_cert_out = NULL;         /* The file output stream for the cert */
    BIO *bio_pkey_out = NULL;          /* The file output stream for the key */
    R_LIB_CTX *lib_ctx = NULL;                        /* The library context */
    R_CERT_CTX *cert_ctx = NULL;                  /* The certificate context */
    R_CERT *cert = NULL;                                  /* The certificate */
    R_CERT_NAME *name=NULL;            /* The issuer name of new certificate */
    R_PKEY_CTX *pkey_ctx = NULL;                   /* The public key context */
    R_PKEY *pkey = NULL;                                   /* The public key */
    R_TIME_CTX *time_ctx = NULL;                  /* The time module context */
    R_TIME *na_time = NULL;                             /* The notAfter time */
    R_TIME *nb_time = NULL;                            /* The notBefore time */
    R_FORMAT out_form;       /* The output format of the certificate request */
    int sign_type;     /* The signature type with which to sign the new cert */
    int version = 1;                   /* The version of certificate request */
    char *pkeyfile;                              /* The public key file name */
    char *outfile;                                   /* The output file name */
    long days;                /* The number of days the certificate is valid */
    unsigned char serial_number[]={0x43, 0x21, 0x00}; /* The serial number
                                                                    * - 4321 */
    R_ITEM item;                                         /* The item of data */
                                         /* The certificate name as a string */
    char *name_str="C=AU, ST=QLD, L=Brisbane, O=RSA Security, CN=Self Signed";
    int key_bits = 1024;            /* The number of bits for key */

    /* Initialize the global variables */
    pkeyfile = "self_signed.key"; /* The public key file name */
    outfile = "self_signed.cert"; /* The output file name */

    /* Set the defaults */
    out_form = R_FORMAT_BINARY;
    sign_type = R_CR_ID_SHA1_RSA;
    days = 30;

    /* Create the output channels */
    bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);
    if (bio_err == NULL)
    {
        ret = R_ERROR_ALLOC_FAILURE;
        goto done;
    }
    bio_out = BIO_new_fp(stdout, BIO_NOCLOSE);
    if (bio_out == NULL)
    {
        ret = R_ERROR_ALLOC_FAILURE;
        goto done;
    }

    /*
     * Create the library context. Retrieve the custom resource list and create
     * a library context to provide access to all configurable aspects of the
     * library. A user-defined resource list demonstrates how to select modules
     * to include in the resource list and application.
     */
    if ((ret = R_LIB_CTX_new(cert_rl_items, R_RES_FLAG_DEF, &lib_ctx)) !=
        R_ERROR_NONE)
    {
        BIO_printf(bio_err,"Failed to create a library context\n");
        goto done;
    }

    /*
     * This custom resource list supports X.509 certificates only. To configure
     * this sample for WTLS certificates, replace the X.509 resource list item
     * (R_CERT_RES_X509) with the WTLS resource list item (R_CERT_RES_WTLS).
     * Use the WTLS type (R_CERT_TYPE_WTLS) to create the context and
     * certificates.
     */

    /*
     * Generate a public/private key pair. Create a public key context and key
     * object, generate a key pair, and write the key to file.
     */

    /* Create a public key context from which to create the public key */
    ret = R_PKEY_CTX_new(lib_ctx, R_RES_FLAG_DEF, R_PKEY_TYPE_RSA,
        &pkey_ctx);
    if (ret != R_ERROR_NONE)
    {
        BIO_printf(bio_err, "Unable to create a public key context\n");
        goto done;
    }

    /* Generate the key pair */
    BIO_printf(bio_out, "Generating the key pair - may take a few seconds.\n");
    ret = R_PKEY_generate_simple(pkey_ctx, &pkey, R_PKEY_TYPE_RSA, key_bits,
                                 2, R_PKEY_FL_DEFAULT, (R_SURRENDER*)NULL);
    if (ret != R_ERROR_NONE)
    {
        BIO_printf(bio_err, "Failed to generate the key!\n");
        goto done;
    }

    /* Write the key to a file */
    BIO_printf(bio_out, "Writing the generated key to %s\n", pkeyfile);
    bio_pkey_out = BIO_new_file(pkeyfile, "wb");
    if (bio_pkey_out == NULL)
    {
        BIO_printf(bio_err, "Unable to open the file: %s\n", pkeyfile);
        ret = R_ERROR_ALLOC_FAILURE;
        goto done;
    }
    ret = R_PKEY_to_bio(bio_pkey_out, pkey, out_form, NULL);
    if (ret != R_ERROR_NONE)
    {
        BIO_printf(bio_err, "Failed to write the key\n");
        goto done;
    }

    /*
     * The following steps are for setting up time-related functions and
     * calculating the notBefore and notAfter validity time and dates
     * for the certificate.
     */

    /*
     * Create a time context. This is required in order to use any R_TIME_*
     * routines.
     */
    ret = R_TIME_CTX_new(lib_ctx, R_RES_FLAG_DEF, &time_ctx);
    if (ret != R_ERROR_NONE)
    {
        BIO_printf(bio_err, "Unable to create a time context\n");
        goto done;
    }

    /* Create the notBefore time object */
    ret = R_TIME_new(time_ctx, &nb_time);
    if (ret != R_ERROR_NONE)
    {
        BIO_printf(bio_err, "Unable to create the time object\n");
        goto done;
    }

    /*
     * Retrieve the current time. In this sample the current time is used for
     * the notBefore time.
     */
    ret = R_TIME_time(nb_time);
    if (ret != R_ERROR_NONE)
    {
        BIO_printf(bio_err, "Unable to retrieve the current time\n");
        goto done;
    }

    /* Copy the notBefore time */
    ret = R_TIME_dup(nb_time, &na_time);
    if (ret != R_ERROR_NONE)
    {
        BIO_printf(bio_err, "Unable to create the time object\n");
        goto done;
    }

    /* Set the notAfter time to current time plus validity period */
    ret = R_TIME_offset(na_time, na_time, 60*60*24*days);
    if (ret != R_ERROR_NONE)
    {
        BIO_printf(bio_err, "Unable to offset time\n");
        goto done;
    }

    /*
     * Create a certificate context and a new certificate object. All
     * certificate operations require a certificate context, providing access
     * to the certificate functionality. The certificate object stores all the
     * certificate information. The information in the various fields of the
     * certificate is set against the certificate object in the next step of
     * this sample. For WTLS operations, replace the X.509 resource list item
     * (R_CERT_RES_X509) with the WTLS resource list item (R_CERT_RES_WTLS)
     * and use the WTLS type (R_CERT_TYPE_WTLS).
     */
    ret = R_CERT_CTX_new(lib_ctx, R_RES_FLAG_DEF, R_CERT_TYPE_X509, &cert_ctx);
    if (ret != R_ERROR_NONE)
    {
        BIO_printf(bio_err, "Unable to create a certificate context\n");
        goto done;
    }

    ret = R_CERT_new(cert_ctx, R_CERT_TYPE_X509, &cert);
    if (ret != R_ERROR_NONE)
    {
        BIO_printf(bio_err, "Failed to create a new certificate object\n");
        goto done;
    }

    /*
     * Set all the certificate information against the certificate object.
     * All the fields of the certificate must be set against the certificate
     * object. If generating a WTLS certificate, do not include the steps that
     * set the serial number.
     */

    /* Enter the version of the certificate structure */
    ret = R_CERT_set_info(cert, R_CERT_INFO_VERSION, &version);
    if (ret != R_ERROR_NONE)
    {
        BIO_printf(bio_err, "Failed to set version\n");
        goto done;
    }

    /* Convert the name string into an R_CERT_NAME structure */
    ret = R_CERT_NAME_from_string(cert_ctx, name_str, &name);
    if (ret != R_ERROR_NONE)
    {
        BIO_printf(bio_err, "Failed to create name from string\n");
        goto done;
    }

    /* Store the subject name */
    ret = R_CERT_set_info(cert, R_CERT_INFO_SUBJECT_R_CERT_NAME, name);
    if (ret != R_ERROR_NONE)
    {
        BIO_printf(bio_err, "Failed to set the subject name\n");
        goto done;
    }

    /*
     * Store the issuer name. This is the subject in this case because
     * this is a self-signed certificate.
     */
    ret = R_CERT_set_info(cert, R_CERT_INFO_ISSUER_R_CERT_NAME, name);
    if (ret != R_ERROR_NONE)
    {
        BIO_printf(bio_err, "Failed to set the subject name\n");
        goto done;
    }

    /* Enter the public key for the certificate request */
    ret = R_CERT_set_info(cert, R_CERT_REQ_INFO_R_PKEY, pkey);
    if (ret != R_ERROR_NONE)
    {
        BIO_printf(bio_err, "Failed to set the public key\n");
        goto done;
    }

    /* Set the serial number into an R_ITEM */
    item.data = serial_number;
    item.len = 2;

    /*  The serial number in the certificate */
    ret = R_CERT_set_info(cert, R_CERT_INFO_SERIAL_NUMBER, &item);
    if ( ret != R_ERROR_NONE)
    {
        BIO_printf(bio_err, "Failed to set the serial number in the"
            " certificate\n");
        goto done;
    }

    /* Store the notBefore validity time as a UTC string */
    ret = R_CERT_not_before_from_R_TIME(cert, nb_time);
    if (ret != R_ERROR_NONE)
    {
        BIO_printf(bio_err, "Failed to set the notBefore time to the"
            " certificate\n");
        goto done;
    }

    /* Store the notAfter validity time as a UTC string */
    ret = R_CERT_not_after_from_R_TIME(cert, na_time);
    if (ret != R_ERROR_NONE)
    {
        BIO_printf(bio_err, "Failed to set the notAfter time to the"
            " certificate\n");
        goto done;
    }

    /*
     * Sign the certificate with the private key, using the specified signature
     * algorithm. All certificate information is stored in the certificate
     * object.
     */
    ret = R_CERT_sign(cert, pkey, sign_type);
    if (ret != R_ERROR_NONE)
    {
        BIO_printf(bio_err, "Failed to sign the certificate\n");
        goto done;
    }

    /*
     * Write the certificate to file. Open the output stream and print the
     * certificate into the stream.
     */

    /* Open the output file */
    bio_cert_out = BIO_new_file(outfile, "wb");
    if (bio_cert_out == NULL)
    {
        BIO_printf(bio_err, "Unable to open the file: %s\n", outfile);
        ret = R_ERROR_ALLOC_FAILURE;
        goto done;
    }

    /* Output the certificate to file */
    BIO_printf(bio_out, "Writing the generated certificate to %s\n", outfile);
    ret = R_CERT_write(cert, bio_cert_out, out_form, NULL);
    if (ret != R_ERROR_NONE)
    {
        BIO_printf(bio_err, "Failed to write the certificate\n");
    }

    /*
     * Clean up. Report errors if there is an output stream using both the
     * error and the string representation. Destroy the dynamically allocated
     * objects and return an exit code.
     */
done:
    /* Display the error value */
    if ((ret != R_ERROR_NONE) && (bio_err != NULL))
    {
        BIO_printf(bio_err, "Error: (%d)\n", ret,
            R_LIB_CTX_get_error_string(lib_ctx, R_RES_MOD_ID_LIBRARY, ret));
    }
    if (name != NULL)
    {
        R_CERT_NAME_free(name);
    }

    if (cert != NULL)
    {
        R_CERT_free(cert);
    }

    if (cert_ctx != NULL)
    {
        R_CERT_CTX_free(cert_ctx);
    }

    if (pkey != NULL)
    {
        R_PKEY_free(pkey);
    }

    if (pkey_ctx != NULL)
    {
        R_PKEY_CTX_free(pkey_ctx);
    }

    if (nb_time != NULL)
    {
        R_TIME_free(nb_time);
    }
    if (na_time != NULL)
    {
        R_TIME_free(na_time);
    }
    if (time_ctx != NULL)
    {
        R_TIME_CTX_free(time_ctx);
    }

    if (bio_cert_out != NULL)
    {
        BIO_free(bio_cert_out);
    }
    if (bio_pkey_out != NULL)
    {
        BIO_free(bio_pkey_out);
    }

    if (lib_ctx != NULL)
    {
        R_LIB_CTX_free(lib_ctx);
    }

    if (bio_out != NULL)
    {
        BIO_free(bio_out);
    }
    if (bio_err != NULL)
    {
        BIO_free(bio_err);
    }

    return(R_ERROR_EXIT_CODE(ret));
}


Copyright (c) 1999-2005 RSA Security Inc. All rights reserved. 072-001001-2100-001-000 - 2.1