Encrypt and decrypt text file using C++ (original) (raw)

Last Updated : 23 Jul, 2025

Encryption in cryptography is a process by which a plain text or a piece of information is converted into ciphertext or a text which can only be decoded by the receiver for whom the information was intended. The algorithm that is used for the process of encryption is known as a cipher. It helps protect consumer information, emails, and other sensitive data from unauthorized access to it and secures communication networks. Presently there are many options to choose from and find the most secure algorithm which meets our requirements.

Decryption: Decryption is the process of converting a meaningless message (Ciphertext) into its original form (Plaintext). It works by applying the conversion algorithm opposite of the one that is used to encrypt the data. The same key is required to decrypt the information back to its normal form.

Types of Cryptography: There are two types of cryptography:

In this article, symmetric cryptography is used to encrypt and decrypt data.

Approach: Let's discuss the approach in detail before proceeding to the implementation part:

Below is the implementation of the above approach:

C++ `

// C++ program for the above approach

#include <bits/stdc++.h> #include using namespace std;

// encdec class with encrypt() and // decrypt() member functions class encdec { int key;

// File name to be encrypt
string file = "geeksforgeeks.txt";
char c;

public: void encrypt(); void decrypt(); };

// Definition of encryption function void encdec::encrypt() { // Key to be used for encryption cout << "key: "; cin >> key;

// Input stream
fstream fin, fout;

// Open input file
// ios::binary- reading file
// character by character
fin.open(file, fstream::in);
fout.open("encrypt.txt", fstream::out);

// Reading original file till
// end of file
while (fin >> noskipws >> c) {
    int temp = (c + key);

    // Write temp as char in
    // output file
    fout << (char)temp;
}

// Closing both files
fin.close();
fout.close();

}

// Definition of decryption function void encdec::decrypt() { cout << "key: "; cin >> key; fstream fin; fstream fout; fin.open("encrypt.txt", fstream::in); fout.open("decrypt.txt", fstream::out);

while (fin >> noskipws >> c) {

    // Remove the key from the
    // character
    int temp = (c - key);
    fout << (char)temp;
}

fin.close();
fout.close();

}

// Driver Code int main() { encdec enc; char c; cout << "\n"; cout << "Enter Your Choice : -> \n"; cout << "1. encrypt \n"; cout << "2. decrypt \n"; cin >> c; cin.ignore();

switch (c) {
case '1': {
    enc.encrypt();
    break;
}
case '2': {
    enc.decrypt();
    break;
}
}

}

`

Output: