Encrypting & Decrypting Text Files with a Key

  • Thread starter Thread starter the_storm
  • Start date Start date
  • Tags Tags
    files Text
AI Thread Summary
The discussion revolves around creating a program to encrypt and decrypt text files using a key. The encryption process involves shifting the ASCII values of characters based on a key, while the decryption reverses this process. Users report issues with decryption resulting in corrupted files and infinite loops when running the program in Visual Studio. Suggestions include opening files in binary mode to avoid character discrepancies and correcting the method of reading characters from the input file. The conversation emphasizes the importance of ensuring proper character handling and debugging techniques to resolve these issues.
the_storm
Messages
42
Reaction score
0
Hey guys how r u .. :) I hope u all r happy.
I have an assignment to write a program to encrypt and decrypt a txt file using a key that I will choose

here is the problem
Code:
Consider the problem of encrypting a sequence of characters {A0, A1, A2, .. Ai….An-1} into another sequence {B0, B1, B2, ..Bi….Bn-1}. It is possible to encrypt a single character (Ai) (i.e. convert it to another character (Bi)) by shifting its ASCII value by an integer displacement (di). For example, if Ai = ‘A’ with ASCII of 65 and di = 12 then Bi = ‘M’ with an ASCII value of 65 + 12 = 77.
With Ai and Bi of type unsigned char, the encryption can be done by computing:

Bi = unsigned char (int (Ai) + di).  (Encryption process)

Of course we can retrieve the character back by the inverse process:
 
Ai = unsigned char (int (Bi) – di).  (Decryption process)

Given a message of (n) characters (A0,A1,…An-1) and a ‘key’ in the form of a string of (n) characters (K0,K1,…Kn-1), we can encrypt the message by computing (n) displacements (d0,d1,…dn-1) and applying the transformation Bi = unsigned char (int (Ai) + di)  where i= 0,1,2,..,n-1. A possible displacement is given by di = int (Ki) - 32.

In practice, the message could be very long (e.g. a file of characters) with a number of characters (M) much longer than the key length (n). In this case, we apply the displacements (d0,d1,…dn-1) to the first block of (n) characters, then to the 2nd block of (n) characters , and so on. Hence for a long sequence (A0,A1,…AM-1) with M >> n, a character Aj is  encrypted using a displacement  di where i = j mod n.

Implement the following: 
1.	A function unsigned char EncChar (unsigned char C, int j, int flag) to receive a character (C) and its index (j) in the message. If flag = 0, the character is plain and we intend to encrypt it. In this case, the function returns the encrypted character by adding a displacement  di obtained from a character Ki in a secret key in the form of a string of length (n) characters. 
Notice that this function is also used for decryption when flag = 1 so we return the decrypted character by subtracting the displacement di.
2.	A function void encfile (string infile, string outfile) to encrypt/decrypt a whole text file of characters and write the result to another file. This function will call the character level function EncChar for each input character.

3.	A main function to:
•	receive the input and output file names from the user 
•	Set a flag = 0 to encrypt (add di) and flag = 1 to decrypt (subtract di)
•	Call the file encryption function encfile.

Hints:
•	Set the key string and its length as global variables. For example:
string key = "5002,22enuJdeW";
int n = key.length();

•	The key length should not exceed 32 characters.  
•	A character Ki in the string is obtained as key[i]



I understand it well and I wrote my program and compiled it with no errors but it has problems .. The first one is when I try to decrypt the file again I don't get the file right at all ... in other words I lose the file... and the other problem when I press ctrl + f5 in my visual studio to compile and run the program keep working and as if it entered to infinite loop ... but when I build the batch it doesn't do the same ...
here is my program code...


Code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
unsigned char EncChar(unsigned char c, int j, bool flag);
string key = "Iam an enginner";
const int n = key.length();
void main()
{
	string infile, outfile;
	bool flag;
	unsigned char y;
	char x;
	int charPlace = 0;
	ifstream source;
	ofstream target;


	//Getting the name of the files fron the user
	cout << "Enter the name of the input file: " << endl;
	cin >> infile;
	cout << "Enter the name of the output file: " << endl;
	cin >> outfile;
	cout << "Do you want to encrypt of decrypt the file? \n for encryption please write 0 for decryption write 1" << endl;
	cin >> flag;
	source.open(infile.c_str());
	target.open(outfile.c_str());
	source.get(x);
	while (!source.eof())
	{
		y = EncChar(x, charPlace, flag);
		charPlace++;
		target.put(y);
		source.get(x);
	}
	source.close();
	target.close();
		
}

unsigned char EncChar(unsigned char c, int j, bool flag)
{
	
	unsigned char s;
	//int d[n];
	int k ;// the corresponding index to the char in the key 
	k = j % n;
	//for(int i = 0; i < n; i++)
		//d[i]= int(key[i]) - 32 ;

	if (!flag)
		s = unsigned char(int('c') + (int(key[k])) - 32); 
	else 
		s =	unsigned char(int('c') - (int(key[k])) + 32);
	return s;
}



waiting ur help guys :) thank you anyway
 
Physics news on Phys.org
When you open your input and output files, I think it might be a good idea to open them in binary mode. In text mode, Windows adds a few additional characters. For example, if your string is "one two three\n", Windows actually stores two characters for the newline character - a CR (carriage return, ASCII 13 ) and an LF (line feed, ASCII 10)

When you start the program with <CTRL> F5, it's possible that the program has displayed a prompt in the console and is waiting for input from you. When you open a command prompt (aka DOS window) and run your program, you see the prompts right there.

the_storm said:
string key = "Iam an enginner";
Then you should at least learn how to spell what you claim to be...
 
First of all. I am not claiming that I am an engineer. However, I am just using a key !... It might be I am an engineer, doctor, artist..or even a nonsense sentence... And it won't affect the program...! and even if I am claiming that I will be an engineer, u can't judge if I will be a good or bad engineer from misspelling... about the program, when windows add dome characters when the program decrypts the line or the NWLN character it will reform it as it was...and the program should work correctly without any defects...and about the binary files.. I haven't taken yet this class but now these r my resources which in the assignment and I should use these resources to get the output that I want!
 
Sorry I forgot this. About the waiting in the prompt screen I am sure it isn't waiting for me to put an input or a variable because I am the one who wrote the code and understand when it is asking for input and when it is not... and u can see the code and try it at ur own machine!
 
the_storm said:
First of all. I am not claiming that I am an engineer.
However, I am just using a key !... It might be I am an engineer, doctor, artist..or even a nonsense sentence... And it won't affect the program...! and even if I am claiming that I will be an engineer, u can't judge if I will be a good or bad engineer from misspelling
Maybe not, but businesses do. If you sent a letter to a software firm asking about an "enginner" position, the chances are pretty good that they would not call you in for an interview. Engineers are supposed to be good with details, such as the name of their profession.
the_storm said:
... about the program, when windows add dome characters when the program decrypts the line or the NWLN character it will reform it as it was...
And how exactly will that happen if your program writes one character ('\n') but reads two characters ('\r', '\n')? Your encryption/decryption routine expects a one-to-one pairing between the characters in the plaintext and those in the ciphertext.
the_storm said:
and the program should work correctly without any defects
...and about the binary files.. I haven't taken yet this class but now these r my resources which in the assignment and I should use these resources to get the output that I want!

One error I see is that you are calling istream.get incorrectly. In your code you have
Code:
source.get(x);
where x is of type char. None of the overloaded get methods on the string class have an argument of type char. The overload you are using takes a parameter that is a reference to a char; i.e., type char &. The method you should use takes no parameters and returns an int.
Code:
x = source.get();

Here x should be of type int, which can be cast to a char if need be.

As far as opening a file in binary mode, that's easy to do. Here's the code for opening an input file in binary mode and read mode.
Code:
source.open(infile.c_str(), ifstream::binary | ifstream::in);
 
the_storm said:
Sorry I forgot this. About the waiting in the prompt screen I am sure it isn't waiting for me to put an input or a variable because I am the one who wrote the code and understand when it is asking for input and when it is not... and u can see the code and try it at ur own machine!
Put a breakpoint in your program, and press F5. When execution stops at the breakpoint, press F10 to single-step through your code to find out where it's getting hung up.

Your program is a console app. When you start it in Visual Studio you might not be looking at the command prompt window, which is where the prompt will appear. After you start your program in VS, make sure you are looking at the command window.
 

Similar threads

Replies
1
Views
1K
Replies
8
Views
2K
Replies
24
Views
3K
Replies
2
Views
4K
Replies
3
Views
2K
Back
Top