RSA BSAFE Micro Edition Suite

Streamlined security for mobile and embedded devices

Search  Print

cert_smpl.c

/* $Id: cert_smpl.c,v 1.18 2005/02/07 01:38:21 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 "cert_smpl.h"

/*
 * 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_out = NULL;            /* The standard output stream */
    BIO *bio_err = NULL;            /* The standard error output stream */
    BIO *bio_cert_out = NULL;       /* The file output stream for
                                     * certificates */
    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_CERT_REQ_CTX *req_ctx = NULL; /* The certificate request context */
    R_CERT_REQ *req = NULL;         /* The certificate request */
    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 */
    int version = 1;                /* The version of certificate request */
    char *outfile;                  /* The output file name */
    long days;                      /* The number of days for which the
                                     * certificate is valid */
    unsigned int consumed_len;
    unsigned char serial_number[]={0x65, 0x43, 0x00}; /* The serial number
                                                       * - 6543 */
    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=Simple Sample";

    /* Initialize the global variables */
    outfile = "sample.cert"; /* output filename */

    /*
     * Create BIOs to stderr and stdout. BIOs are the Basic Input/Output
     * mechanism provided by RSA and are recommended for all input and output
     * from applications.
     */
    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 default resource list and
     * create a library context to provide access to all configurable aspects
     * of the library.
     */
    if ((ret = PRODUCT_LIBRARY_NEW(PRODUCT_DEFAULT_RESOURCE_LIST(), 0,
         &lib_ctx)) != R_ERROR_NONE)
    {
        BIO_printf(bio_err, "Unable to create library context\n");
        goto done;
    }

    /*
     * Load the signer's private key. Create a public key context and a public
     * key object and load the key into the object from memory.
     */
    /* 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;
    }

    /*
     * This is the key that signs the certificate (that is, the CA
     * private key)
     */
    ret = R_PKEY_from_binary( pkey_ctx, R_PKEY_FL_DEFAULT, R_PKEY_TYPE_RSA,
                              sizeof(pkey_data), pkey_data,
                              &consumed_len, &pkey );
    if (ret != R_ERROR_NONE)
    {
        BIO_printf(bio_err, "R_PKEY_from_binary failure - for pkey\n");
        goto done;
    }

    /*
     * Load the certificate request. Create a certificate request context and
     * a certificate request object and load the request into the object from
     * memory.
     */

    /* Create a new certificate request context */
    ret = R_CERT_REQ_CTX_new(lib_ctx, R_RES_FLAG_DEF, R_CERT_REQ_TYPE_PKCS10,
              &req_ctx);

    if (ret != R_ERROR_NONE)
    {
        BIO_printf(bio_err, "Unable to create a certificate request context \n");
        goto done;
    }

    /* Read the certificate request */
    ret = R_CERT_REQ_from_binary(req_ctx, R_CERT_REQ_FLAG_BY_REFERENCE,
                                 R_CERT_REQ_TYPE_PKCS10, sizeof(cert_req),
                                 (const unsigned char *)cert_req,
                                 &consumed_len, &req);
    if (ret != R_ERROR_NONE)
    {
        BIO_printf(bio_err, "Failed to read the request\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 by adding the notBefore time and the validity
     * period
     */
    days = 300;
    ret = R_TIME_offset(na_time, na_time, 60*60*24*days);
    if (ret != R_ERROR_NONE)
    {
        BIO_printf(bio_err, "Unable to offset the time\n");
        goto done;
    }

    /*
     * Create a certificate context and a new certificate object. All
     * certificate operations require a certificate context. This context
     * provides 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. To generate an X.509 certificate, use
     * the R_CERT_TYPE_X509 identifier. To generate a WTLS certificate, use the
     * R_CERT_TYPE_WTLS identifier.
     */
    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 the certificate context\n");
        goto done;
    }

    /*
     * Issue a new certificate. The certificate request contains the subject
     * name and public key. This information is entered straight into the
     * certificate. Before signing, the serial number, issuer name and validity
     * times are added to complete the certificate.
     */
    ret = R_CERT_REQ_to_R_CERT(req, cert_ctx, R_CERT_TYPE_X509, &cert);
    if (ret != R_ERROR_NONE)
    {
        BIO_printf(bio_err, "Failed to create the certificate from the"
            " request\n");
        goto done;
    }

    /*
     * Set the remaining certificate information against the certificate
     * object. The remaining fields are issuer name, serial and version
     * numbers, and the notBefore and notAfter times. 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 the version\n");
        goto done;
    }

    /*
     * Convert the name string into an R_CERT_NAME structure. This name is
     * used for the issuer name of the certificate. Usually the issuer name
     * is the subject name of the CA's certificate; but for simplicity use a
     * fixed string.
     */
    ret = R_CERT_NAME_from_string(cert_ctx, name_str, &name);
    if (ret != R_ERROR_NONE)
    {
        BIO_printf(bio_err, "Failed to create the name from the string\n");
        goto done;
    }

    /* Store the issuer name */
    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;
    }

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

    /* Store 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 certificate\n");
        goto done;
    }

    /*
     * Store the notBefore validity time as a Universal Time, Coordinated
     * (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 Universal Time, Coordinated
     * (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. All the certificate information is now in the
     * certificate object. Sign the certificate information with the private
     * key using the specified signature algorithm.
     */
    ret = R_CERT_sign(cert, pkey, R_CR_ID_SHA1_RSA);
    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. In this instance, binary format. */
    BIO_printf(bio_out, "Writing the generated certificate to %s\n", outfile);
    ret = R_CERT_write(cert, bio_cert_out, R_FORMAT_BINARY, NULL);
    if (ret != R_ERROR_NONE)
    {
        BIO_printf(bio_err, "Failed to write the certificate\n");
    }

done:
    /*
     * 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.
     */
    if ((ret != R_ERROR_NONE) && (bio_err != NULL))
    {
        BIO_printf(bio_out, "ERROR: (%d) %s\n", ret,
            R_LIB_CTX_get_error_string(lib_ctx, R_RES_MOD_ID_LIBRARY, ret));
    }

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

    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 (req != NULL)
    {
        R_CERT_REQ_free(req);
    }
    if (req_ctx != NULL)
    {
        R_CERT_REQ_CTX_free(req_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 (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