Thursday, 5 September 2013

Encryption and Decryption using Blowfish in C

Encryption and Decryption using Blowfish in C

I've spent hours on this and can't figure out what I am doing wrong. I am
able to encrypt a file, but when I decrypt it is partially readable. I.e,
if a file has apple, when I encrypt it, and then try to decrypt it, I get
this in the decrypted file:
aBple ^?^@<91>çÄ Ï^_×h^@^@<80>^?^C^A^@^@^@À<85>?cÿ^?^@^@^@^@^@^@ÿ^?^@^@
<87>?cÿ^?^@^@0<87>?cÿ^?^@^@^@^@^@^@^D^@^@
Please take a look at my code and give me a hand please. I truly tried my
best.
The BF key has already been set, I am able to open the file, that is some
assumptions you can make.
Variable declarations:
unsigned char key[] = "0123456789012345"; //USING A CONSTANT KEY FOR
NOW SINCE I AM IN TESTING STAGE
unsigned char from[64];
char buffer[64];
unsigned char to[64] = {0};
unsigned char dc[64] = {0};
unsigned char iv[16] = {0};
char *inFile = NULL;
char *outFile = NULL;
BF_KEY bf_key;
To decrypt here is my code:
if(dopt==1)
{
int outFileDesc = open(outFile,O_WRONLY| O_CREAT, 0777);
FILE *stream;
char *contents;
int fileSize = 0;
//Open the stream. Note "b" to avoid DOS/UNIX new line conversion.
stream = fopen(inFile, "rb");
//Steak to the end of the file to determine the file size
fseek(stream, 0L, SEEK_END);
fileSize = ftell(stream);
fseek(stream, 0L, SEEK_SET);
//Allocate enough memory (add 1 for the \0, since fread won't add it)
contents = malloc(fileSize+1);
//Read the file
size_t size=fread(contents,fileSize,1,stream);
contents[size]=0; // Add terminating zero.
printf("Read THE FILE AS %s\n", contents);
char * newto = malloc(fileSize);
BF_cfb64_encrypt(contents, newto, fileSize, &bf_key, iv, &enc,
BF_DECRYPT);
write(outFileDesc, newto, fileSize);
printf("DECRYPTED TO %s", newto);
close(fileDesc);
close(outFileDesc);
memset(iv, 0, sizeof(iv));
// Close the file
fclose(stream);
}
To encrypt this is my code:
if(eopt==1)
{
fileDesc = open(inFile, O_RDONLY);
int outFileDesc = open(outFile, O_WRONLY | O_CREAT, 0777);
int readSoFar=0;
if(outFileDesc<0)
{
printf("ERROR CREATING/READING OUT FILE. NOW EXITING");
exit(1);
}
while(readSoFar = read(fileDesc, buffer, 64)>0)
{
strcpy(from, buffer);
BF_cfb64_encrypt(from, to, sizeof(from), &bf_key, iv, &enc,
BF_ENCRYPT);
write(outFileDesc, to, sizeof(to));
}
close(fileDesc);
close(outFileDesc);
memset(iv, 0, sizeof(iv));
enc = 0;
}

No comments:

Post a Comment