RSA BSAFE Crypto-C

Cryptographic Components for C

Search

aes.c

/* $Id: aes.c,v 1.8 2004/12/03 02:08:40 sparki Exp $ */
/*
 * Copyright (C) 1998-2004 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.
 *
 *
 */

/*
 * This program encrypts and decrypts using AES, utilizing CBC with padding.
 */

#include "bsafe.h"
#include "bsfutil.h"
#include "demoutil.h"

#define KEY_SIZE 16    /* number of bytes in the key */
#define BLOCK_SIZE 16

#ifdef CRYPTOC_APP
#define MAIN aesMain
#else
#define MAIN main
#endif

int MAIN(int argc, char *argv[])
{
  int status = 0;
  B_KEY_OBJ aesKey = (B_KEY_OBJ)NULL_PTR;
  B_ALGORITHM_OBJ aesEncrypter = (B_ALGORITHM_OBJ)NULL_PTR;
  B_ALGORITHM_OBJ aesDecrypter = (B_ALGORITHM_OBJ)NULL_PTR;
  B_ALGORITHM_OBJ randomAlgorithm = (B_ALGORITHM_OBJ)NULL_PTR;

  unsigned char initVector[BLOCK_SIZE];

  ITEM aesKeyItem = {NULL, 0};

  unsigned char *dataToEncrypt = (unsigned char *)"Encrypt this sentence.";
  unsigned int dataToEncryptLen;

  unsigned char *encryptedData = NULL_PTR;
  unsigned int outputLenUpdate, outputLenFinal, outputLenTotal;
  unsigned int encryptedDataLen;

  unsigned char *decryptedData = NULL_PTR;
  unsigned int decryptedLenUpdate, decryptedLenFinal;
  unsigned int decryptedLenTotal, decryptedDataLen;

  B_ALGORITHM_METHOD *AES_CHOOSER[] = {
    &AM_AES_CBC_ENCRYPT,
    &AM_AES_CBC_DECRYPT,
    (B_ALGORITHM_METHOD *)NULL_PTR
/* This will fix a problem that the IA64 compiler finds when *
 * seeing a short chooser list */
#ifdef IA64_FORCE_LARGE
    IA64_FORCE_LARGE
#endif
  };




  do {
    /* The RSA_* demo code utilities are described in common/include/demoutil.h.
       This procedure simply checks the command-line arguments for input or
       output options. */
    if ((status = RSA_SetOptions (argc, argv)) != 0)
      break;

    RSA_PrintMessage ("AES algorithm:  Encryption phase \n");
    RSA_PrintMessage ("================================ \n");

    /*  Create an algorithm object. */
    if ((status = B_CreateAlgorithmObject (&aesEncrypter)) != 0)
      break;

    /*  Initialize a random algorithm object using a procedure described in
        samples/common/include/bsfutil.h  */
    if ((status = RSA_CreateRandomAlgorithmObject (&randomAlgorithm)) != 0)
      break;

    /*  Generate a random initialization vector  */
   if ((status = B_GenerateRandomBytes
                    (randomAlgorithm, (unsigned char *)initVector, BLOCK_SIZE,
                     (A_SURRENDER_CTX *)NULL_PTR)) != 0)
      break;

    RSA_PrintBuf ("Random Initialization Vector", initVector, sizeof (initVector));

    /*  Set the algorithm to a type that does AES encryption
        in CBC mode with padding.  */
    if ((status = B_SetAlgorithmInfo
                    (aesEncrypter, AI_AES_CBCPad, (POINTER)initVector)) != 0)
      break;

    /*  Create a key object  */
    if ((status = B_CreateKeyObject (&aesKey)) != 0)
      break;

    /*  Set the key object with a random AES key  */
    aesKeyItem.len = KEY_SIZE;
    aesKeyItem.data = T_malloc (aesKeyItem.len);
    if ((status = (aesKeyItem.data == NULL_PTR)) != 0)
      break;

    if ((status = B_GenerateRandomBytes
                    (randomAlgorithm, aesKeyItem.data, aesKeyItem.len,
                     (A_SURRENDER_CTX *)NULL_PTR)) != 0)
      break;

    RSA_PrintBuf ("Random AES key", aesKeyItem.data, aesKeyItem.len);

    if ((status = B_SetKeyInfo (aesKey, KI_Item, (POINTER)&aesKeyItem)) != 0)
      break;

    /*  Let's zeroize the memory and free it up immediately after
        setting the key for security reasons.  */
    if (aesKeyItem.data != NULL_PTR) {
      T_memset (aesKeyItem.data, 0, aesKeyItem.len);
      T_free (aesKeyItem.data);
      aesKeyItem.data = NULL_PTR;
      aesKeyItem.len = 0;
    }

    /*  Init */
    if ((status = B_EncryptInit (aesEncrypter, aesKey, AES_CHOOSER,
                                 (A_SURRENDER_CTX *)NULL_PTR)) != 0)
      break;

    /*  Update */
    dataToEncryptLen = T_strlen ((char *)dataToEncrypt) + 1;
    RSA_PrintBuf ("Data To Encrypt", dataToEncrypt, dataToEncryptLen);

    encryptedDataLen = dataToEncryptLen + BLOCK_SIZE;
    encryptedData = T_malloc (encryptedDataLen);
    if ((status = (encryptedData == NULL_PTR)) != 0) {
      status = RSA_DEMO_E_ALLOC;
      break;
    }

    if ((status = B_EncryptUpdate
                    (aesEncrypter, encryptedData, &outputLenUpdate,
                     encryptedDataLen, dataToEncrypt, dataToEncryptLen,
                     (B_ALGORITHM_OBJ)NULL_PTR,
                     (A_SURRENDER_CTX *)NULL_PTR)) != 0)
      break;

    /*  Final */
    if ((status = B_EncryptFinal
                    (aesEncrypter, encryptedData + outputLenUpdate,
                     &outputLenFinal, encryptedDataLen - outputLenUpdate,
                     (B_ALGORITHM_OBJ)NULL_PTR,
                     (A_SURRENDER_CTX *)NULL_PTR)) != 0)
      break;

    outputLenTotal = outputLenUpdate + outputLenFinal;

    RSA_PrintBuf ("Encrypted Data", encryptedData, outputLenTotal);

    RSA_PrintMessage ("\nAES algorithm:  Decryption phase \n");
    RSA_PrintMessage ("================================ \n");

    if ((status = B_CreateAlgorithmObject (&aesDecrypter)) != 0)
      break;

    /*  Use the same AI and parameters as for encryption */
    if ((status = B_SetAlgorithmInfo
                    (aesDecrypter, AI_AES_CBCPad, (POINTER)initVector)) != 0)
      break;

    /*  Use the same key as for encryption */
    if ((status = B_DecryptInit (aesDecrypter, aesKey, AES_CHOOSER,
                                 (A_SURRENDER_CTX *)NULL_PTR)) != 0)
      break;

    /*  Set the buffer that will take the decrypted data to be the same size
        as the encrypted data's buffer.  */
    decryptedDataLen = encryptedDataLen;
    decryptedData = T_malloc (decryptedDataLen);
    if ((status = (decryptedData == NULL_PTR)) != 0) {
      status = RSA_DEMO_E_ALLOC;
      break;
    }

    if ((status = B_DecryptUpdate
                    (aesDecrypter, decryptedData, &decryptedLenUpdate,
                     decryptedDataLen, encryptedData, outputLenTotal,
                     (B_ALGORITHM_OBJ)NULL_PTR,
                     (A_SURRENDER_CTX *)NULL_PTR)) != 0)
      break;

    if ((status = B_DecryptFinal
                    (aesDecrypter, decryptedData + decryptedLenUpdate,
                     &decryptedLenFinal, decryptedDataLen - decryptedLenUpdate,
                     (B_ALGORITHM_OBJ)NULL_PTR,
                     (A_SURRENDER_CTX *)NULL_PTR)) != 0)
      break;

    decryptedLenTotal = decryptedLenUpdate + decryptedLenFinal;

    RSA_PrintBuf ("Decrypted Data", decryptedData, decryptedLenTotal);

    if ((decryptedLenTotal == dataToEncryptLen) &&
        (T_memcmp (dataToEncrypt, decryptedData, decryptedLenTotal)) == 0) {
      RSA_PrintMessage ("Success!  ");
      RSA_PrintMessage ("The decrypted data matches the original data.\n");
    } else {
      RSA_PrintMessage ("The decrypted data does not match the original data.");
      status = RSA_DEMO_E_INFO_DOES_NOT_VERIFY;
    }
  } while (0);

  if (status != 0)
    RSA_PrintError ("aes example", status);

  /*  Done with the key and algorithm objects, so destroy them.  */
  B_DestroyKeyObject (&aesKey);
  B_DestroyAlgorithmObject (&aesEncrypter);
  B_DestroyAlgorithmObject (&randomAlgorithm);
  B_DestroyAlgorithmObject (&aesDecrypter);

  /*  Free up any memory allocated, save it to a file or print it out first
      if you need to save it.  */
  if (encryptedData != NULL_PTR)
    T_free (encryptedData);

  if (decryptedData != NULL_PTR)
    T_free (decryptedData);

  if (aesKeyItem.data != NULL_PTR) {
    T_memset (aesKeyItem.data, 0, aesKeyItem.len);
    T_free (aesKeyItem.data);
    aesKeyItem.data = NULL_PTR;
    aesKeyItem.len = 0;
  }

  return (status);
} /*  end main  */

Copyright (c) 1999-2005 RSA Security Inc. All rights reserved. 068-001001-6210-001-000 - 6.2.1