RSA BSAFE Micro Edition Suite

Streamlined security for mobile and embedded devices

Search  Print

r_hmac.c

/* $Id: r_hmac.c,v 1.27 2005/02/08 05:57:17 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.
 *
 *
 */

/*
 * @file r_hmac.c
 * This sample demonstrates how to perform Hashed Message Authentication
 * Code (HMAC) operations.
 *
 * For example, to:
 *
 * Create a HMAC from a string using SHA1:
 * r_hmac -alg SHA1 -key 012345678 -string "hello world"
 */

#include "r_prod.h"
#include "cryp_mod.h"

/* The maximum HMAC buffer size for this sample */
#define MAX_HMAC_SIZE 128

/* Usage message */
static char *r_hmac_usage[] =
{
    "usage: r_hmac [options]\n",
    "where options are:\n",
    " -alg value      - HMAC digest-type, one of SHA1 (default) or MD5\n",
    " -key value      - Key value to include in HMAC\n",
    " -string value   - String to compute HMAC from\n",
#ifdef NO_SOFTWARE_CRYPTO
    " -no_fips140     - Use non FIPS140 operating mode\n",
    " -fips140_ssl    - Use FIPS140 SSL operating mode\n",
#endif /* NO_SOFTWARE_CRYPTO */
    " -help           - Print this help menu\n",
    NULL
};

static int create_mac(BIO *bio_err, R_CR_CTX *ctx, R_CR_ALG_ID alg_id,
    R_SKEY *key, char *string, unsigned char *buf,
    unsigned int *len);
static int verify_mac(BIO *bio_err, R_CR_CTX *ctx, R_CR_ALG_ID alg_id,
    R_SKEY *key, char *string, unsigned char *buf,
    unsigned int len, int *result);

/*
 * 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;
    R_CR_ALG_ID     alg_id;
    int             result;
    BIO             *bio_out    = NULL;
    BIO             *bio_err    = NULL;
    R_RES_LIST      *res_list;
    R_LIB_CTX       *lib_ctx    = NULL;
    R_CR_CTX        *ctx        = NULL;
    char            *string;
    char            *str;
    R_ITEM          key_desc;
    R_SKEY          *key        = NULL;
    unsigned char   buf[MAX_HMAC_SIZE];
    unsigned int    len         = MAX_HMAC_SIZE;
#ifdef NO_SOFTWARE_CRYPTO
    R_FIPS140_OPERATING_MODE_T  operating_mode = FIPS140_MODE;
#endif /* NO_SOFTWARE_CRYPTO */

    /* Set the default values */
    alg_id = R_CR_ID_HMAC_SHA1;
    string = NULL;
    key_desc.data = NULL;
    key_desc.len = 0;

    res_list = PRODUCT_DEFAULT_RESOURCE_LIST();

    /*
     * Create BIOs to stdout and stderr. BIOs are the Basic Input/Output
     * mechanism provided by RSA and are recommended for all input and output
     * from applications.
     */
    bio_out = BIO_new_fp(stdout, BIO_NOCLOSE);
    bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);

    if ((bio_out == NULL) || (bio_err == NULL))
    {
        ret = R_ERROR_ALLOC_FAILURE;
        goto end;
    }


    /* Skip the program name */
    argc--;
    argv++;

    /* Parse the command line parameters */
    while (argc >= 1)
    {
        if (Strcmp(*argv, "-key") == 0)
        {
            if (--argc < 1)
            {
                goto bad;
            }
            key_desc.data = (unsigned char *) *(++argv);
            key_desc.len = Strlen((char *) key_desc.data);
        }
        else if (Strcmp(*argv, "-alg") == 0)
        {
            if (--argc < 1)
            {
                goto bad;
            }

            str = *(++argv);
            if (Strcmp(str, "SHA1") == 0)
            {
                alg_id = R_CR_ID_HMAC_SHA1;
            }
            else if (Strcmp(str, "MD5") == 0)
            {
                alg_id = R_CR_ID_HMAC_MD5;
            }
            else
            {
                BIO_printf(bio_err, "Unknown algorithm\n");
                ret = R_ERROR_BAD_PARAMETER;
                goto bad;
            }
        }
        else if (Strcmp(*argv, "-string") == 0)
        {
            if (--argc < 1)
            {
                goto bad;
            }
            string = *(++argv);
        }
#ifdef NO_SOFTWARE_CRYPTO
        else if (Strcmp(*argv, "-no_fips140") == 0)
        {
            operating_mode = NON_FIPS140_MODE;
        }
        else if (Strcmp(*argv, "-fips140_ssl") == 0)
        {
            operating_mode = FIPS140_SSL_MODE;
        }
#endif /* NO_SOFTWARE_CRYPTO */
        else if (Strcmp(*argv, "-help") == 0)
        {
            goto bad;
        }
        else
        {
            BIO_printf(bio_err, "Unknown option %s\n", *argv);
            goto bad;
        }
        argc--;
        argv++;
    }

    /* Validate the command line options */
    if ((string == NULL) || (key_desc.data == NULL))
    {
        BIO_printf(bio_err, "No data to process, or key to process with\n");
        goto bad;
    }

    if (0)
    {
        char **pp;
bad:
        for (pp = r_hmac_usage; (*pp != NULL); pp++)
        {
            BIO_printf(bio_err, *pp);
        }
        goto end;
    }

    /*
     * Create the library context to provide access to all configurable aspects
     * of the library
     */
#ifdef NO_SOFTWARE_CRYPTO
    /*
     * For FIPS140 shared library builds set the operating mode required
     * first
     */
    switch (operating_mode)
    {

    case FIPS140_MODE:
        CRYPTOC_FIPS140_enable_fips140_operating_mode();
        break;

    case NON_FIPS140_MODE:
        CRYPTOC_FIPS140_enable_non_fips140_operating_mode();
        break;

    case FIPS140_SSL_MODE:
        CRYPTOC_FIPS140_enable_fips140_ssl_operating_mode();
        break;
    }
#endif /* NO_SOFTWARE_CRYPTO */
    if ((ret = PRODUCT_LIBRARY_NEW(res_list, R_RES_FLAG_DEF, &lib_ctx)) !=
        R_ERROR_NONE)
    {
        BIO_printf(bio_err, "Unable to create library context\n");
        goto end;
    }

    /* Create a new cryptographic context */
    if ((ret = R_CR_CTX_new(lib_ctx, R_RES_FLAG_DEF, &ctx)) != R_ERROR_NONE)
    {
        BIO_printf(bio_err, "Unable to create cryptographic context\n");
        goto end;
    }

    /*
     * Create a new symmetric key object with the key data specified
     * on the command line
     */
    if ((ret = R_SKEY_new(lib_ctx, R_SKEY_TYPE_GENERIC, &key_desc, &key))
        != R_ERROR_NONE)
    {
        BIO_printf(bio_err, "Unable to create cryptographic key\n");
        goto end;
    }

    /*
     * Compute the HMAC from the data and the key, and print the
     * resulting value
     */
    if ((ret = create_mac(bio_err, ctx, alg_id, key, string, buf, &len)) !=
        R_ERROR_NONE)
    {
        goto end;
    }

    /*
     * Print the Hashed Message Authentication Code (HMAC) computed from
     * the supplied string
     */
    BIO_printf(bio_out, "STRING HMAC RESULT:\n");
    BIO_dump(bio_out, buf, len);

    /*
     * Verify the previously computed HMAC data, and print the result.
     * [Optional].
     */
    if ((ret = verify_mac(bio_err, ctx, alg_id, key, string, buf, len,
        &result)) != R_ERROR_NONE)
    {
        goto end;
    }

    /* Print the result */
    if (result == 0)
    {
        BIO_printf(bio_out, "HMAC VERIFIED\n");
    }
    else
    {
        BIO_printf(bio_out, "HMAC VERIFIY FAILURE\n");
        ret = R_ERROR_FAILED;
    }

end:

   /*
    * 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))
    {
#ifndef NO_CRYPTO_ERR
        BIO_printf(bio_err, "ERROR: (%d) %s\n", ret,
            R_LIB_CTX_get_error_string(lib_ctx, R_RES_MOD_ID_LIBRARY, ret));
#else /* NO_CRYPTO_ERR */
        BIO_printf(bio_err, "ERROR: (%d)\n", ret);
#endif /* NO_CRYPTO_ERR */
    }

    if (key != NULL)
    {
        R_SKEY_free(key);
    }

    if (ctx != NULL)
    {
        R_CR_CTX_free(ctx);
    }

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

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

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

    return(R_ERROR_EXIT_CODE(ret));
}

static int create_mac(BIO * bio_err, R_CR_CTX * ctx, R_CR_ALG_ID alg_id,
    R_SKEY * key, char *string, unsigned char *buf, unsigned int *len)
{
    int     ret;
    R_CR    *hmac_obj = NULL;

    /* Create a new cryptographic object for MAC code generation */
    if ((ret = R_CR_new(ctx, R_CR_TYPE_MAC, alg_id, R_CR_SUB_MAC,
        &hmac_obj)) != R_ERROR_NONE)
    {
        BIO_printf(bio_err, "Unable to create cryptographic object\n");
        goto end;
    }

    /* Load the cryptographic object with a symmetric key */
    if ((ret = R_CR_mac_init(hmac_obj, key)) != R_ERROR_NONE)
    {
        BIO_printf(bio_err, "MAC initialization failure\n");
        goto end;
    }

    /*
     * Compute the HMAC data. In this example, the message is available in one
     * block, so only a single MAC update is required. If the message consists
     * of multiple parts, then multiple calls to mac_update must be made.
     */
    if ((ret = R_CR_mac_update(hmac_obj, (unsigned char *) string,
        Strlen(string))) != R_ERROR_NONE)
    {
        BIO_printf(bio_err, "MAC update failure\n");
        goto end;
    }

    /* Return the HMAC calculated on the data */
    if ((ret = R_CR_mac_final(hmac_obj, buf, len)) != R_ERROR_NONE)
    {
        BIO_printf(bio_err, "MAC final failure\n");
        goto end;
    }

end:

    /*
     * Clean up. Destroy any dynamically allocated objects and return an
     * error code.
     */
    if (hmac_obj != NULL)
    {
        R_CR_free(hmac_obj);
    }

    return (ret);
}

static int verify_mac(BIO * bio_err, R_CR_CTX * ctx, R_CR_ALG_ID alg_id,
    R_SKEY * key, char *string, unsigned char *buf, unsigned int len,
    int *result)
{
    int     ret;
    R_CR    *hmac_obj = NULL;

    /* Create a new cryptographic object for MAC code verification */
    if ((ret = R_CR_new(ctx, R_CR_TYPE_MAC, alg_id, R_CR_SUB_VERIFY,
        &hmac_obj)) != R_ERROR_NONE)
    {
        BIO_printf(bio_err, "Unable to create cryptographic object\n");
        goto end;
    }

    /* Load the cryptographic object with a symmetric key */
    if ((ret = R_CR_verify_mac_init(hmac_obj, key)) != R_ERROR_NONE)
    {
        BIO_printf(bio_err, "MAC verification initialization failure\n");
        goto end;
    }

    /*
     * Compute the HMAC data. In this example, the message is available in one
     * block so only a single MAC update is required. If the message consists
     * of multiple parts, then multiple calls to verify_mac_update must be
     * made.
     */
    if ((ret = R_CR_verify_mac_update(hmac_obj, (unsigned char *) string,
        Strlen(string))) != R_ERROR_NONE)
    {
        BIO_printf(bio_err, "MAC verify update failure\n");
        goto end;
    }

    /*
     * Compare the newly computed HMAC against the previously computed
     * value.
     */
    if ((ret = R_CR_verify_mac_final(hmac_obj, buf, len, result)) !=
        R_ERROR_NONE)
    {
        BIO_printf(bio_err, "MAC verify final failure\n");
        goto end;
    }

end:

    /*
     * Clean up. Destroy any dynamically allocated objects and return an
     * error code.
     */
    if (hmac_obj != NULL)
    {
        R_CR_free(hmac_obj);
    }

    return (ret);
}

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