test_dec.c 2.35 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 *input_block;
  unsigned char *output_block;
  unsigned char * whole_data;
  int i;
  int error=0;
  int keyLen, blockLen;
  char *keyMaterial;
  char *iv;


  if ((argc < 4) && (argc > 1)){
    fprintf(stderr,"Usage: test_dec inputfile outputfile num_bytes\n");
    exit(1);
  }
  else{
    
    if(argc <2){
      infilename = strdup("output.bin");
    }
    else{
      infilename = strdup(argv[1]);
    }
    
    if(argc <3){
      outfilename = strdup("deciphered.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 ( FILE_SIZE*sizeof(unsigned char));
  output_block = (unsigned char *) malloc (FILE_SIZE*sizeof(unsigned char));
  
  //key parameters
  
  keyLen = 128;
  keyMaterial = "abcdef0123456789abcdef0123456789";
  //iv = "00000000000000000000000000000000";
  iv =          "000102030405060708090a0b0c0d0e0f";
  blockLen = 128;

  
  if(makeKeyEqvtInv(&key, DIR_DECRYPT , keyLen, blockLen, keyMaterial) != TRUE){
    fprintf(stderr,"error in computing key\n");
    exit(1);
  }
  
  
		
  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");
    
  }

  if(blockDecryptEqvtInv(&cipher, &key, whole_data, FILE_SIZE*8, output_block)<0){
      fprintf(stderr, "cipher decryption error \n");
      exit(1);
    }
    else{
      fprintf(stderr,"Computed inverse cipher\n");
      if(fwrite(output_block, sizeof(char), FILE_SIZE,  outptr) != FILE_SIZE){
	fprintf(stderr, "writing error\n");
	exit(1);
      }
      fprintf(stderr,"Wrote file\n");
    }
  return 1;
}