test_enc.c 2.54 KB
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "rijndael-api-ref.h"
#define BLOCK_SIZE 128
#define FILE_SIZE 512

int main(int argc, char **argv){
  FILE *inptr;
  FILE *outptr;
  char *infilename = NULL;
  char *outfilename = NULL;
  int num_bytes=0;
  keyInstance key;
  cipherInstance cipher;
  unsigned char *output_block;
  unsigned char * whole_data;
  int i,j,k;
  int error=0;
  int keyLen, blockLen;
  char *keyMaterial;
  char *iv;

  if ((argc < 4) && (argc > 1)){
    fprintf(stderr,"Usage: test_enc inputfile outputfile num_bytes\n");
    exit(1);
  }
  else{
    
    if(argc <2){
      infilename = strdup("input.bin");
    }
    else{
      infilename = strdup(argv[1]);
    }
    
    if(argc <3){
      outfilename = strdup("output.bin");
    }
    else{
      outfilename = strdup(argv[2]);
    }
    
    if(argc <4){
      num_bytes = FILE_SIZE;
    }
    else{
      num_bytes = atoi(argv[3]);
    }
  }

  printf("arguments= %s %s %d\n", infilename, outfilename, num_bytes);
  
  if((inptr = fopen(infilename, "rb")) == NULL){
    fprintf(stderr, "error opening file\n");
  }
  outptr = fopen(outfilename, "wb");

  whole_data = (unsigned char *) malloc ( num_bytes*sizeof(unsigned char));
  output_block = (unsigned char *) malloc (num_bytes*sizeof(unsigned char));
  
  //key parameters
  
  keyLen = 128;
  keyMaterial = "abcdef0123456789abcdef0123456789";
  
  //cbc hardcoded!
  iv =   "000102030405060708090a0b0c0d0e0f";
  blockLen = 128;

  /* make key */
  if(makeKey(&key, DIR_ENCRYPT , keyLen, blockLen,  keyMaterial) != TRUE){
    fprintf(stderr,"error in computing key\n");
    exit(1);
  }
  
  /* initialise parameters */	
  if ((error = cipherInit (&cipher, MODE_CBC, iv, blockLen))!= TRUE) {
    fprintf(stderr,"cipherInit error %d \n", error);
    exit(1);
  }
  
  while (fread((void *)whole_data, sizeof(char), FILE_SIZE, inptr) == FILE_SIZE){
    fprintf(stderr,"read file\n");
    
  }
  
  /*encrypt */
  if(blockEncrypt(&cipher, &key, whole_data, FILE_SIZE*8, output_block)!= FILE_SIZE*8){
      fprintf(stderr, "cipher encryption error \n");
      exit(1);
    }
    else{
      fprintf(stderr,"Computed Cipher\n");
      if(fwrite(output_block, sizeof(char), FILE_SIZE,  outptr) != FILE_SIZE){
	fprintf(stderr, "writing error\n");
	exit(1);
      }
      /* write out for debugging */
      /*
      k=0;
      for(i=0; i< FILE_SIZE/8; i++){
	for (j=0; j< 4; j++){
	  fprintf(outptr, "%02x", output_block[k]);
	  k++;
	}
	fprintf(outptr, "\n");
      }
      */
      fprintf(stderr,"Wrote file\n");
    }
  return 1;
}