| RSA BSAFE Micro Edition Suite |
Streamlined security for mobile and embedded devices |
 
![]() |
/* $Id: r_ciph.c,v 1.28 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_ciph.c * This sample demonstrates symmetric cipher encryption and decryption. * * For example, to: * * Encrypt and decrypt a string with DES_CBC: * r_ciph -alg DES_CBC -key "01234567" -iv "abcdefgh" -string "hello world" * * Encrypt and decrypt a string with AES_128_CBC: * r_ciph -alg AES_128_CBC -key "0123456789abcdef" -iv "fedcba9876543210" * -string "hello world" */ #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_ciph_usage[] = { "usage: r_ciph [options]\n", "where options are:\n", " -alg value - Cipher algorithm, (default is DES_CBC)\n", " -key value - Key value to use with the cipher\n", " -iv value - Initialization vector for the cipher (optional)\n", " -np - Turn off block padding for the cipher\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_CR_ALG_ID alg_id, R_SKEY *key, R_ITEM *iv, int np, unsigned char *string, unsigned char *buf, unsigned int *mlen); static int decrypt_data(BIO *bio_err, R_CR_CTX *ctx, R_CR_ALG_ID alg_id, R_SKEY *key, R_ITEM *iv, int np, unsigned char *data, unsigned int dlen, unsigned char *buf, unsigned int *mlen); /* * 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. * See @ref R_ERROR_IDS for valid values. */ int main(int argc, char **argv) { int ret = R_ERROR_NONE; int np = 1; int ciph_alg; 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_data = { 0, NULL }; R_SKEY *key; R_ITEM iv_data = { 0, NULL }; R_ITEM *iv; 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 */ /* Set the default values */ ciph_alg = R_CR_ID_DES_CBC; string = NULL; key = NULL; iv = &iv_data; 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, "-alg") == 0) { if (--argc < 1) { goto bad; } str = *(++argv); if ((ret = R_CR_ID_from_string(str, &ciph_alg)) != R_ERROR_NONE) { BIO_printf(bio_err, "Bad algorithm identifier: %s\n", str); goto bad; } } else if (Strcmp(*argv, "-key") == 0) { if (--argc < 1) { goto bad; } key_data.data = (unsigned char *) *(++argv); key_data.len = Strlen((char *) key_data.data); } else if (Strcmp(*argv, "-iv") == 0) { if (--argc < 1) { goto bad; } iv_data.data = (unsigned char *) *(++argv); iv_data.len = Strlen((char *) iv_data.data); } else if (Strcmp(*argv, "-np") == 0) { np = 0; } 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_data.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_ciph_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_data, &key)) != R_ERROR_NONE) { BIO_printf(bio_err, "Unable to create cryptographic key\n"); goto end; } /* Encrypt the string with the symmetric key */ if ((ret = encrypt_data(bio_err, ctx, ciph_alg, key, iv, np, (unsigned char *) string, buf, &len)) != R_ERROR_NONE) { goto end; } if (!np) { BIO_printf(bio_out, "NOTE: in non-padding mode, trailing bytes may\n"); BIO_printf(bio_out, "be truncated during decryption by this sample\n"); } /* Print the encrypted data */ if (len > 0) { BIO_printf(bio_out, "ENCRYPTED MESSAGE:\n"); BIO_dump(bio_out, buf, len); } else { BIO_printf(bio_out, "ENCRYPTED MESSAGE: length 0\n"); ret = R_ERROR_FAILED; goto end; } /* * Retrieve the decrypted string with the symmetric key */ if ((ret = decrypt_data(bio_err, ctx, ciph_alg, key, iv, np, 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 (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 encrypt_data(BIO *bio_err, R_CR_CTX *ctx, R_CR_ALG_ID alg_id, R_SKEY *key, R_ITEM *iv, int np, unsigned char *string, unsigned char *buf, unsigned int *mlen) { int ret = R_ERROR_NONE; R_CR *enc_obj = NULL; unsigned int len; unsigned int tlen; unsigned char *tmp; /* * Create a new symmetric cryptographic object initialized with * the cipher to use when encrypting */ if ((ret = R_CR_new(ctx, R_CR_TYPE_CIPHER, alg_id, R_CR_SUB_NONE, &enc_obj)) != R_ERROR_NONE) { BIO_printf(bio_err, "Unable to create encryption object\n"); goto end; } /* * Set the padding mode. By default block padding is always turned on, and * this is equivalent to np == 1) for the cryptographic object. */ if ((ret = R_CR_set_info(enc_obj, R_CR_INFO_ID_BLOCK_PADDING, (void *) &np)) != R_ERROR_NONE) { BIO_printf(bio_err, "Unable to set padding mode\n"); goto end; } /* * Load the symmetric key and the Initialization Vector into the * cryptographic object */ if ((ret = R_CR_encrypt_init(enc_obj, key, iv)) != R_ERROR_NONE) { BIO_printf(bio_err, "Unable to initialize encryption object\n"); goto end; } /* * Encrypt the data. This operation encrypts the data excluding the * last block. */ if ((ret = R_CR_encrypt_update(enc_obj, string, Strlen((char *) string), buf, &tlen)) != R_ERROR_NONE) { BIO_printf(bio_err, "Encrypt update failure\n"); goto end; } /* Move to the end of the buffer */ tmp = buf + tlen; /* * Perform the final operation on the buffer. This operation encrypts the * last block of data, and adds padding if required. */ if ((ret = R_CR_encrypt_final(enc_obj, tmp, &len)) != R_ERROR_NONE) { BIO_printf(bio_err, "Encrypt final failure\n"); goto end; } /* Return the length of the encrypted data */ (*mlen) = tlen + len; end: /* * Clean up. Destroy any dynamically allocated objects and return an * error code. */ if (enc_obj != NULL) { R_CR_free(enc_obj); } return (ret); } static int decrypt_data(BIO *bio_err, R_CR_CTX *ctx, R_CR_ALG_ID alg_id, R_SKEY *key, R_ITEM *iv, int np, unsigned char *data, unsigned int dlen, unsigned char *buf, unsigned int *mlen) { int ret = R_ERROR_NONE; R_CR *dec_obj = NULL; unsigned int len; unsigned int tlen; unsigned char *tmp; /* * Create a new symmetric cryptographic object initialized with * the cipher to use when decrypting */ if ((ret = R_CR_new(ctx, R_CR_TYPE_CIPHER, alg_id, R_CR_SUB_NONE, &dec_obj)) != R_ERROR_NONE) { BIO_printf(bio_err, "Unable to create decryption object\n"); goto end; } /* * Set the padding mode. By default block padding is always turned on, * and this is equivalent to np == 1) for the cryptographic object. */ if ((ret = R_CR_set_info(dec_obj, R_CR_INFO_ID_BLOCK_PADDING, (void *) &np)) != R_ERROR_NONE) { BIO_printf(bio_err, "Unable to set padding mode\n"); goto end; } /* * Load the symmetric key and the Initialization Vector into the * cryptographic object */ if ((ret = R_CR_decrypt_init(dec_obj, key, iv)) != R_ERROR_NONE) { BIO_printf(bio_err, "Unable to initialize decryption object\n"); goto end; } /* * Decrypt the data. This operation decrypts the data excluding the * last block. */ if ((ret = R_CR_decrypt_update(dec_obj, data, dlen, buf, &tlen)) != R_ERROR_NONE) { BIO_printf(bio_err, "Decrypt update failure\n"); goto end; } /* Move to the end of the buffer */ tmp = buf + tlen; /* * Perform the final operation on the buffer. This operation decrypts the * last block of data, and removes padding if required. */ if ((ret = R_CR_decrypt_final(dec_obj, tmp, &len)) != R_ERROR_NONE) { BIO_printf(bio_err, "Decrypt final failure\n"); goto end; } /* Return the length */ (*mlen) = tlen + len; end: /* * Clean up. Destroy any dynamically allocated objects and return * an error code. */ if (dec_obj != NULL) { R_CR_free(dec_obj); } return (ret); }