Sunday, November 15, 2009

Chap12[C]h Encrypting/Decrypting file

Write a program to encrypt/decrypt a file using:
An offset cipher: In an offset cipher each character from the source file is offset with a fixed value and then written to the target file. For example, if character read from the source file is ‘A’, then convert this into a new character by offsetting ‘A’ by a fixed value, say 128, and then writing the new character to the target file.


Program to encrypt file

#include "stdio.h"
void main()
{
FILE *fp,*ft;
char ch;

fp=fopen("c:\\ctxt\\cipher.txt","r");
if(fp==NULL)
{
puts("Cannot open file");
exit();
}
ft=fopen("c:\\ctxt\\cipher2.txt","w");
if(ft==NULL)
{
puts("Cannot open file");
exit();
}

while(1)
{
ch=fgetc(fp);
if(ch==EOF)
break;
ch+=128;
fputc(ch,ft);
};
fclose(fp);
fclose(ft);
remove("c:\\ctxt\\cipher.txt");
rename("c:\\ctxt\\cipher2.txt","c:\\ctxt\\cipher.txt");
}

Program to decrypt the same file


#include "stdio.h"
void main()
{
FILE *fp,*ft;
char ch;
fp=fopen("c:\\ctxt\\cipher.txt","r");
if(fp==NULL)
{
puts("Cannot open file");
exit();
}
ft=fopen("c:\\ctxt\\cipher2.txt","w");
if(ft==NULL)
{
puts("Cannot open file");
exit();
}
while(1)
{
ch=fgetc(fp);
if(ch==EOF)
break;
ch-=128;
fputc(ch,ft);
};
fclose(fp);
fclose(ft);
remove("c:\\ctxt\\cipher.txt");
rename("c:\\ctxt\\cipher2.txt","c:\\ctxt\\cipher.txt");
}

1 comment:

  1. somebody plzz explain the line "ch+=128"and"ch-=128" and how do they encrypt and decrypt.

    ReplyDelete