- C++ Programming Examples
- C++ Programming Examples
- C++: Hello World
- C++: Get Input
- C++: Print Integer
- C++: Add two numbers
- C++: Add, Sub, Multiply, Div
- C++: Add Digits
- C++: Find Average and Percentage
- C++: Find Arithmetic Mean
- C++: Sum of n Natural Numbers
- C++: Sum of n Numbers
- C++: Square's Area and Perimeter
- C++: Rectangle's Area and Perimeter
- C++: Triangle's Area and Perimeter
- C++: Area and Circumference
- C++: Find Simple Interest
- C++: Fahrenheit to Celsius
- C++: Celsius to Fahrenheit
- C++: Print Prime Numbers
- C++: Reverse a Number
- C++: Swap Two Numbers
- C++: Print Multiplication Table
- C++: Find Factorial of a Number
- C++: Find Factors of a Number
- C++: Find HCF and LCM
- C++: Create a Calculator
- C++: Count Digits in a Number
- C++: First and Last Digit Sum
- C++: Product of Number Digits
- C++: Sum of Squares of Digits
- C++: Interchange Digits of Number
- C++ if-else Programs
- C++: Check Even or Odd
- C++: Check Prime or Not
- C++: Check Alphabet or Not
- C++: Check Vowel or Not
- C++: Check Leap Year or Not
- C++: Check Reverse equals Original
- C++: Check Perfect Number
- C++: Check Palindrome or Not
- C++: Check Armstrong or Not
- C++: Divisibility Test
- C++: Find Labor Wage
- C++: Find Discounted Price
- C++: Find Shipping Charge
- C++: Find Telephone Bills
- C++: Calculate Student Grade
- C++: Largest of Two Numbers
- C++: Largest of Three Numbers
- C++ Number Conversion
- C++: Decimal to Binary
- C++: Decimal to Octal
- C++: Decimal to Hexadecimal
- C++: Binary to Decimal
- C++: Binary to Octal
- C++: Binary to Hexadecimal
- C++: Octal to Decimal
- C++: Octal to Binary
- C++: Octal to Hexadecimal
- C++: Hexadecimal to Decimal
- C++: Hexadecimal to Binary
- C++: Hexadecimal to Octal
- C++ Pattern Programs
- C++: Pattern Programs
- C++: Print Diamond Pattern
- C++: Print Floyd's Triangle
- C++: Print Pascal's Triangle
- C++ Array Programs
- C++: 1D Array Program
- C++: Linear Search
- C++: Binary Search
- C++: Largest Element in an Array
- C++: Smallest Element in an Array
- C++: Find Second Largest Element
- C++: Find Second Smallest Element
- C++: Sum of All Elements
- C++: Multiply All Elements
- C++: Element in Even Position
- C++: Element in Odd Position
- C++: Print Even Numbers in Array
- C++: Print Odd Numbers in Array
- C++: Count Even or Odd Numbers
- C++: Sum of Even or Odd Numbers
- C++: Count Positive, Negative, Zero
- C++: Reverse an Array
- C++: Insert an Element
- C++: Delete an Element
- C++: Merge two Arrays
- C++: Bubble Sort
- C++: Selection Sort
- C++: Insertion Sort
- C++: Common Elements
- C++: 2D Array Programs
- C++: Add Two Matrices
- C++: Subtract Two Matrices
- C++: Transpose Matrix
- C++: Multiply Two Matrices
- C++: 3D Array Programs
- C++ String Programs
- C++: Print String
- C++: Find String Length
- C++: Compare Two Strings
- C++: Copy String
- C++: String Concatenation
- C++: Reverse a String
- C++: Delete Vowels from a String
- C++: Delete a Word from a String
- C++: Count Characters in a String
- C++: Count Words in a String
- C++: Frequency of Words
- C++: Remove Spaces from Strings
- C++: Sort a String
- C++: Uppercase to Lowercase
- C++: Lowercase to Uppercase
- C++: Swap Two Strings
- C++: Check the Anagram or Not
- C++: Capitalize All Words in a String
- C++: Get Numbers from a String
- C++ File Programs
- C++: Read a File
- C++: Write Content to a File
- C++: Append Data to a File
- C++: Read and Display File
- C++: Copy a File
- C++: Merge Two Files
- Count Characters in a File
- C++: Capitalize Every Word
- C++: List Files in Directory
- C++: Delete a File
- C++: Encrypt and Decrypt a File
- C++ Misc Programs
- C++: Print ASCII Value
- C++: Add Binary Numbers
- C++: Generate Random Numbers
- C++: Print a Smiling Face
- C++: Days into Years and Months
- C++: Add Two Numbers using Pointer
- C++: Print Fibonacci Series
- C++: Generate Armstrong Numbers
- C++: Find nCr and nPr
- C++: Get IP Address
- C++: Print Date and Time
- C++: Shutdown and Restart Computer
- C++ Programming Tutorial
- C++ Tutorial
C++ Program to Encrypt and Decrypt a File
In this article, you will learn and get code for file encryption and decryption. That is, code for encrypting textual file data (content).and another code to decrypt the same data from a text file.
What do encryption and decryption mean?
Data encryption is the process of converting data from its original form to a coded form. The coded form of the original data cannot be read by an unauthorized person.
Decryption of data means converting data from its coded form to its original form.
Only an authorized person can access encrypted data.
Note: Only an authorized person knows the decryption key. A decryption key is a password or formula that is used to convert ciphertext to plaintext.
Note: Encrypted data is known as "cyphertext," whereas decrypted data (original data) is known as "plaintext."
Therefore, in simple language, converting data from plaintext to ciphertext is known as data encryption. Data decryption is the process of converting data from cyphertext to plaintext.
Things to Do Before the Program
Because the program given below encrypts the data in a text file and then further decrypts the same data with another program, In our current directory, we must create a text file called fresherearth.txt.
The current directory is the directory where the C++ source code is saved. Therefore, I'm going to save the program to encrypt and decrypt a file in the cpp programs folder. Then, in the same folder, it creates a file named fresherearth.txt with the following content inside it:
username = fresherearthUser password = fresherearthPassword
Here is the snapshot of the folder "cpp programs" that contains the file "fresherearth.txt":
And here is the snapshot of the opened file, fresherearth.txt:
Now let's move on to the program given below, to encrypt the data of this newly created file and then further decrypt the same data.
Encrypt a File in C++
To encrypt a file's content in C++ programming, you have to ask the user to enter the name of the file (with extension). Then, as shown in the program below, encrypt the content contained within the file.
#include<iostream> #include<fstream> #include<stdio.h> using namespace std; int main() { char fileName[30], ch; fstream fps, fpt; cout<<"Enter the Name of File: "; gets(fileName); fps.open(fileName, fstream::in); if(!fps) { cout<<"\nError Occurred, Opening the Source File (to Read)!"; return 0; } fpt.open("tmp.txt", fstream::out); if(!fpt) { cout<<"\nError Occurred, Opening/Creating the tmp File!"; return 0; } while(fps>>noskipws>>ch) { ch = ch+100; fpt<<ch; } fps.close(); fpt.close(); fps.open(fileName, fstream::out); if(!fps) { cout<<"\nError Occurred, Opening the Source File (to write)!"; return 0; } fpt.open("tmp.txt", fstream::in); if(!fpt) { cout<<"\nError Occurred, Opening the tmp File!"; return 0; } while(fpt>>noskipws>>ch) fps<<ch; fps.close(); fpt.close(); cout<<"\nFile '"<<fileName<<"' Encrypted Successfully!"; cout<<endl; return 0; }
This program was built and runs under the Code::Blocks IDE. Here is its sample run:
Now enter the name of the file, say, fresherearth.txt, and press the ENTER key to encrypt its data. Here is the final snapshot of the sample run:
When you open the file fresherearth.txt, the data (content) inside it is encrypted. Here is a snapshot of the opened file, fresherearth.txt:
As you can see from the above snapshot, the data in the file fresherearth.txt cannot be read by any unknown person, that is, a person who does not know the decryption key.
The decryption key is the formula used while encrypting the file, that is, adding 100 to each and every character. So to decrypt, we have to subtract 100 from each and every character. The file tmp.txt holds encrypted text.
The fstream library allows working with files. It is defined in the fstream header file.
The open() function receives one or two arguments. The first argument is required, and that is the name of the file. The second argument is file opening mode. So the statement given below:
fps.open(fileName, fstream::in);
opens the file in reading mode only. The user enters the name of a file, which is saved in the fileName variable. The file opening mode, fstream::in opens a file in reading mode.
And the file opening mode, fstream::out, opens a file in writing mode. If the file does not already exist, it is created.
The statement,
fps>>noskipws>>ch
reads data from a file in a character-by-character manner without skipping white spaces.
The main logic in the above program is:
- The user is prompted to enter the file's name, such as fresherearth.txt.
- opens the file (in reading mode) entered by the user.
- creates a file named tmp.txt
- Character-by-character reading of the contents of the file fresherearth.txt.
- Adds 100 and writes to the tmp.txt file while reading the character.
- That is, in the tmp.txt file, we have the same content as in fresherearth.txt. Instead, each character has an ASCII value, 100 more than the original one.
- Both file streams are closed.
- opens the codecracker.txt file in writing mode.
- opens the file tmp.txt in reading mode.
- Copies the content of tmp.txt (the encrypted content of the fresherearth.txt file) to the fresherearth.txt file
Decrypt a File in C++
Now let's use the cyphertext available in the tmp.txt file with the decryption formula (subtracting 100 from each character) to decrypt the data of a file, fresherearth.txt, with the help of the following program:
#include<iostream> #include<fstream> #include<stdio.h> using namespace std; int main() { char fileName[30], ch; fstream fps, fpt; cout<<"Enter the Name of File: "; gets(fileName); fps.open(fileName, fstream::out); if(!fps) { cout<<"\nError Occurred while Opening the Source File!"; return 0; } fpt.open("tmp.txt", fstream::in); if(!fpt) { cout<<"\nError Occurred while Opening/Creating tmp File!"; return 0; } while(fpt>>noskipws>>ch) { ch = ch-100; fps<<ch; } fps.close(); fpt.close(); cout<<"\nFile '"<<fileName<<"' Decrypted Successfully!"; cout<<endl; return 0; }
Here is the initial snapshot of the sample run:
Now, as shown in the screenshot below, enter the name of the file, say fresherearth.txt, to decrypt its content:
After executing the above program, you should see the same file, which is named fresherearth.txt. Then your data will be restored in its original form, or it will be decrypted. Here is a snapshot of the opened file:
Note: You can create and use your own algorithm for encryption and decryption. It is up to you. The program given above provides you with an idea about the topic.
Short Message on Encrypting and Decrypting Files
To encrypt a file entered by the user, first open the file using the function open(). And read the content of the file in a character-by-character manner. At the time of reading, create some algorithm to encrypt the content of the file. While encrypting, place the content (in a character-by-character manner) in a temporary file, say tmp.txt.
After putting all the encrypted content in a tmp.txt file, copy its content to the original file. And later, use the file tmp.txt to decrypt the content of the fresherearth.txt file.
Same Program in Other Language
« Previous Program Next Program »