| RSA BSAFE Micro Edition Suite |
Streamlined security for mobile and embedded devices |
 
![]() |
/* $Id: r_asym.c,v 1.35 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_asym.c * * This sample demonstrates asymmetric cipher encryption using the RSA * algorithm. The RSA public and private keys can be supplied separately * or together in the same file, but must be in binary format. * * For example, to: * * Encrypt and decrypt a string: * r_aysm -priv_key priv.ber -pub_key pub.ber -string "hello world" * * where: priv.ber = RSA private key in binary format * pub.ber = RSA public key in binary format */ #include "r_prod.h" #include "cryp_mod.h" /* The maximum key buffer size for this sample */ #define MAX_KEY_SIZE 1024 /* Usage message */ static char *r_asym_usage[] = { "usage: r_asym [options]\n", "where options are:\n", " -priv_key file - File containing the RSA private key (binary format)\n", " -pub_key file - File containing the RSA public key (binary format)\n", " -key file - File containing both public and private keys\n", " -string value - String to encrypt and decrypt\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 encrypt_data(BIO *bio_err, R_CR_CTX *ctx, R_PKEY_CTX *pkey_ctx, char *pub_file, unsigned char *string, unsigned char *buf, unsigned int *mlen); static int decrypt_data(BIO *bio_err, R_CR_CTX *ctx, R_PKEY_CTX *pkey_ctx, char *priv_file, unsigned char *data, unsigned int dlen, unsigned char *buf, unsigned int *mlen); static int data_from_file(BIO *bio_err, char *filename, unsigned char **dbuf, unsigned int *dlen); /* * 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; BIO *bio_out = NULL; BIO *bio_err = NULL; R_RES_LIST *res_list = PRODUCT_DEFAULT_RESOURCE_LIST(); R_LIB_CTX *lib_ctx = NULL; R_CR_CTX *ctx = NULL; R_PKEY_CTX *pkey_ctx = NULL; char *string; char *priv_file; char *pub_file; unsigned char buf[MAX_KEY_SIZE]; unsigned int len = MAX_KEY_SIZE; #ifdef NO_SOFTWARE_CRYPTO R_FIPS140_OPERATING_MODE_T operating_mode = FIPS140_MODE; #endif /* NO_SOFTWARE_CRYPTO */ /* The private key file location */ priv_file = NULL; /* The public key file location */ pub_file = NULL; /* The data string to encrypt */ string = NULL; /* * 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; } /* Bypass the program name from the argument list */ argc--; argv++; /* Parse the command line parameters */ while (argc >= 1) { if (Strcmp(*argv, "-priv_key") == 0) { if (--argc < 1) { goto bad; } priv_file = *(++argv); } else if (Strcmp(*argv, "-pub_key") == 0) { if (--argc < 1) { goto bad; } pub_file = *(++argv); } else if (Strcmp(*argv, "-key") == 0) { if (--argc < 1) { goto bad; } pub_file = *(++argv); priv_file = pub_file; } 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 ((priv_file == NULL) || (pub_file == NULL) || (string == NULL)) { BIO_printf(bio_err,"No keys or data to process\n"); goto bad; } /* Display the help menu if an invalid command line option was entered */ if (0) { char **pp; bad: for (pp = r_asym_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 asymmetric key context */ if ((ret = R_PKEY_CTX_new(lib_ctx, R_RES_FLAG_DEF, R_PKEY_TYPE_RSA, &pkey_ctx)) != R_ERROR_NONE) { BIO_printf(bio_err, "Unable to create key context\n"); goto end; } /* Encrypt the string with the public key */ if ((ret = encrypt_data(bio_err, ctx, pkey_ctx, pub_file, (unsigned char *)string, buf, &len)) != R_ERROR_NONE) { goto end; } /* Print the encrypted data */ BIO_printf(bio_out, "ENCRYPTED MESSAGE:\n"); BIO_dump(bio_out, buf, len); /* Retrieve the decrypted string with the private key */ if ((ret = decrypt_data(bio_err, ctx, pkey_ctx, priv_file, buf, len, buf, &len)) != R_ERROR_NONE) { goto end; } /* Print the decrypted data */ BIO_printf(bio_out, "DECRYPTED MESSAGE:\n"); BIO_dump(bio_out, buf, len); 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 (pkey_ctx != NULL) { R_PKEY_CTX_free(pkey_ctx); } 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)); } /* * Encrypts a string using the RSA asymmetric encryption algorithm. * * @param bio_err [In] The BIO for error messages. * @param ctx [In] The cryptographic context reference. * @param pkey_ctx [In] The asymmetric key context reference. * @param pub_file [In] The public key file name string. * @param string [In] The data to encrypt. * @param buf [Out] The output buffer for encrypted data. * @param mlen [Out] The length of encrypted data written to <i>buf</i>. * * @returns R_ERROR_NONE indicates success.<br> * See @ref R_ERROR_IDS for valid values. */ static int encrypt_data(BIO *bio_err, R_CR_CTX *ctx, R_PKEY_CTX *pkey_ctx, char *pub_file, unsigned char *string, unsigned char *buf, unsigned int *mlen) { int ret = R_ERROR_NONE; R_CR *enc_obj = NULL; R_PKEY *pkey = NULL; unsigned char *dbuf = NULL; unsigned char *tmp; unsigned int dlen; unsigned int consumed_len; /* Read the key from a file and store in binary format */ if ((ret = data_from_file(bio_err, pub_file, &dbuf, &dlen)) != R_ERROR_NONE) { goto end; } /* * Create an R_PKEY object from the binary key data. Extract the public key * information from the binary data and load into a key object. This * function will move the data pointer to the end of the buffer, so pass in * a copy in case the key data is required later. */ tmp = dbuf; if ((ret = R_PKEY_from_public_key_binary(pkey_ctx, R_PKEY_FL_BY_REFERENCE, R_PKEY_TYPE_RSA, dlen, (const unsigned char *) tmp, &consumed_len, &pkey)) != R_ERROR_NONE) { BIO_printf(bio_err, "Unable to read public key from binary\n"); goto end; } /* * Create a new asymmetric cryptographic object initialized for * RSA public encryption with PKCS #1 padding */ if ((ret = R_CR_new(ctx, R_CR_TYPE_ASYM, R_CR_ID_RSA_PKCS1, R_CR_SUB_PUB_ENC, &enc_obj)) != R_ERROR_NONE) { BIO_printf(bio_err, "Unable to create cryptographic object\n"); goto end; } /* Load the public RSA key into the cryptographic object */ if ((ret = R_CR_asym_encrypt_init(enc_obj, pkey)) != R_ERROR_NONE) { BIO_printf(bio_err, "Unable to initialize cryptographic object\n"); goto end; } /* Encrypt the data */ if ((ret = R_CR_asym_encrypt(enc_obj, string, Strlen((char *)string), buf, mlen)) != R_ERROR_NONE) { BIO_printf(bio_err,"Unable to encrypt data\n"); goto end; } end: /* * Clean up. Destroy any dynamically allocated objects and return an * error code. */ if (enc_obj != NULL) { R_CR_free(enc_obj); } if (pkey != NULL) { R_PKEY_free(pkey); } if (dbuf != NULL) { Free(dbuf); } return(ret); } /* * Performs the asymmetric decryption operation to retrieve a string value. * * @param bio_err [In] The BIO for error messages. * @param ctx [In] The cryptographic context reference. * @param pkey_ctx [In] The asymmetric key context reference. * @param pub_file [In] The public key file name string. * @param data [In] The data to decrypt. * @param dlen [Out] The length of <i>data</i>. * @param buf [Out] The output buffer for decrypted data. * @param mlen [Out] The length of decrypted data written to <i>buf</i>. * * @returns R_ERROR_NONE indicates success.<br> * See @ref R_ERROR_IDS for valid values. */ static int decrypt_data(BIO *bio_err, R_CR_CTX *ctx, R_PKEY_CTX *pkey_ctx, char *priv_file,unsigned char *data, unsigned int dlen, unsigned char *buf, unsigned int *mlen) { int ret = R_ERROR_NONE; R_CR *dec_obj = NULL; R_PKEY *pkey = NULL; /* * Load the private key data from a file into an R_PKEY. The key * must be stored in binary format. */ if ((ret = R_PKEY_from_file(pkey_ctx, &pkey, priv_file, R_PKEY_TYPE_RSA, R_FORMAT_BINARY)) != R_ERROR_NONE) { BIO_printf(bio_err, "Unable to read private key from file %s\n", priv_file); goto end; } /* * Create a new asymmetric cryptographic object initialized for * RSA private decryption with PKCS #1 padding */ if ((ret = R_CR_new(ctx, R_CR_TYPE_ASYM, R_CR_ID_RSA_PKCS1, R_CR_SUB_PRIV_DEC, &dec_obj)) != R_ERROR_NONE) { BIO_printf(bio_err, "Unable to create cryptographic object\n"); goto end; } /* Load the RSA private key into the cryptographic object */ if ((ret = R_CR_asym_decrypt_init(dec_obj, pkey)) != R_ERROR_NONE) { BIO_printf(bio_err, "Unable to initialize cryptographic object\n"); goto end; } /* Decrypt the data */ if ((ret = R_CR_asym_decrypt(dec_obj, data, dlen, buf, mlen)) != R_ERROR_NONE) { BIO_printf(bio_err, "Unable to decrypt data\n"); goto end; } end: /* * Clean up. Destroy any dynamically allocated objects and return an * error code. */ if (dec_obj != NULL) { R_CR_free(dec_obj); } if (pkey != NULL) { R_PKEY_free(pkey); } return(ret); } /* * Reads binary data from a file into an allocated buffer. * * @param bio_err [In] The BIO for error messages. * @param filename [In] The name of the file to read. * @param dbuf [Out] The allocated data buffer. * @param dlen [Out] The length of the data in <i>dbuf</i>. * * @note It is the calling function's responsibility to free the data * assigned to <i>dbuf</i>. * * @returns R_ERROR_NONE indicates success.<br> * See @ref R_ERROR_IDS for valid values. */ static int data_from_file(BIO *bio_err, char *filename, unsigned char **dbuf, unsigned int *dlen) { int ret = R_ERROR_NONE; int l; unsigned int tlen; BIO *bio_file = NULL; unsigned char buf[512]; /* Create a new BIO for the binary data file */ if ((bio_file = BIO_new_file(filename, "rb")) == NULL) { BIO_printf(bio_err, "Unable to read from file: %s\n", filename); ret = R_ERROR_ALLOC_FAILURE; goto end; } /* Calculate the size of the data in the file */ tlen = 0; while ((l = BIO_read(bio_file, (char *)buf, sizeof(buf))) > 0) { tlen += l; } /* Allocate a buffer for the data */ if (((*dbuf) = (unsigned char *)Malloc(tlen)) == NULL) { BIO_printf(bio_err, "Failed to allocate memory for binary data\n"); ret = R_ERROR_ALLOC_FAILURE; goto end; } /* Reset the BIO to the start of the file */ BIO_reset(bio_file); /* Read the data into the newly allocated buffer */ BIO_read(bio_file, (char *)(*dbuf), tlen); /* Return the length of the data */ (*dlen) = tlen; end: /* Destroy any dynamically allocated objects and return an error code */ if (bio_file != NULL) { /* Free the BIO attached to the file */ BIO_free(bio_file); } return(ret); }