You are on page 1of 13

Encrypt and decrypt text file using C++

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:
Symmetric Cryptography: It is an encryption system where the sender and receiver of a message use a single
common key to encrypt and decrypt messages. Symmetric Key Systems are faster and simpler, but the sender and
receiver have to somehow exchange keys securely. The most popular symmetric-key cryptography system is Data
Encryption System (DES).
Asymmetric Cryptography: Under this system, a pair of keys is used to encrypt and decrypt information. A public
key is used for encryption and a private key is used for decryption. The public key and the private key are different.
Even if the public key is known by everyone, the intended receiver can only decode it because he alone knows the
private key.
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:
A class encdec is defined with two member functions: encrypt () and decrypt (). The name of the file to be encrypted
is the member variable of the class.
Encrypt () function is used to handle the encryption of the input file. The file handling code is included in the
encrypt () function to read the file and write to the file. A new encrypted file called encrypt.txt is generated with all
the encrypted data in it. The encrypted file is encrypted using a key that is being inputted by the user.
Decrypt () function is used to read the encrypted file and decrypt the data and generate a new file decrypt.txt. To
decrypt a file, a key is requested from the user. If the correct key is entered, then the file is successfully decrypted.
The input stream fin is used to read from the file and the output stream fout is used to write to the file.
1. Examples of encrypt and decrypt of cryptography
#include <bits/stdc++.h>
#include <fstream>
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;
}
}
}
Example 2
#include<iostream>
using namespace std;
float en[3][1], de[3][1], a[3][3], b[3][3], msg[3][1], m[3][3];
void getKeyMatrix() { //get key and message from user
int i, j;
char mes[3];
cout<<"Enter 3x3 matrix for key (should have inverse):\n";
for(i = 0; i < 3; i++)
for(j = 0; j < 3; j++) {
cin>>a[i][j];
m[i][j] = a[i][j];
}
cout<<"\nEnter a string of 3 letter(use A through Z): ";
cin>>mes;
for(i = 0; i < 3; i++)
msg[i][0] = mes[i] - 65;
}
void encrypt() { //encrypts the message
int i, j, k;
for(i = 0; i < 3; i++)
for(j = 0; j < 1; j++)
for(k = 0; k < 3; k++)
en[i][j] = en[i][j] + a[i][k] * msg[k][j];
cout<<"\nEncrypted string is: ";
for(i = 0; i < 3; i++)
cout<<(char)(fmod(en[i][0], 26) + 65); //modulo 26 is taken for each element of the matrix obtained by
multiplication
}
void inversematrix() { //find inverse of key matrix
int i, j, k;
float p, q;
for(i = 0; i < 3; i++)
for(j = 0; j < 3; j++) {
if(i == j)
b[i][j]=1;
else
b[i][j]=0;
}
for(k = 0; k < 3; k++) {
for(i = 0; i < 3; i++) {
p = m[i][k];
q = m[k][k];
for(j = 0; j < 3; j++) {
if(i != k) {
m[i][j] = m[i][j]*q - p*m[k][j];
b[i][j] = b[i][j]*q - p*b[k][j];
}
}
}
}
for(i = 0; i < 3; i++)
for(j = 0; j < 3; j++)
b[i][j] = b[i][j] / m[i][i];
cout<<"\n\nInverse Matrix is:\n";
for(i = 0; i < 3; i++) {
for(j = 0; j < 3; j++)
cout<<b[i][j]<<" ";
cout<<"\n";
}
}
void decrypt() { //decrypt the message
int i, j, k;
inversematrix();
for(i = 0; i < 3; i++)
for(j = 0; j < 1; j++)
for(k = 0; k < 3; k++)
de[i][j] = de[i][j] + b[i][k] * en[k][j];
cout<<"\nDecrypted string is: ";
for(i = 0; i < 3; i++)
cout<<(char)(fmod(de[i][0], 26) + 65); //modulo 26 is taken to get the original message
cout<<"\n";
}
int main() {
getKeyMatrix();
encrypt();
decrypt();
}
Example
#include <iostream>
#include <string>
using namespace std;
class Vig {
public:
string k;
Vig(string k) {
for (int i = 0; i < k.size(); ++i) {
if (k[i] >= 'A' && k[i] <= 'Z')
this->k += k[i];
else if (k[i] >= 'a' && k[i] <= 'z')
this->k += k[i] + 'A' - 'a';
}
}
string encryption(string t) {
string output;
for (int i = 0, j = 0; i < t.length(); ++i) {
char c = t[i];
if (c >= 'a' && c <= 'z')
c += 'A' - 'a';
else if (c < 'A' || c > 'Z')
continue;
output += (c + k[j] - 2 * 'A') % 26 + 'A'; //added 'A' to bring it in range of ASCII alphabet [ 65-90 | A-Z ]
j = (j + 1) % k.length();
}
return output;
}
string decryption(string t) {
string output;
for (int i = 0, j = 0; i < t.length(); ++i) {
char c = t[i];
if (c >= 'a' && c <= 'z')
c += 'A' - 'a';
else if (c < 'A' || c > 'Z')
continue;
output += (c - k[j] + 26) % 26 + 'A';//added 'A' to bring it in range of ASCII alphabet [ 65-90 | A-Z ]
j = (j + 1) % k.length();
}
return output;
}
};
int main() {
Vig v("WELCOME");
string ori ="Thisistutorialspoint";
string encrypt = v.encryption(ori);
string decrypt = v.decryption(encrypt);
cout << "Original Message: "<<ori<< endl;
cout << "Encrypted Message: " << encrypt << endl;
cout << "Decrypted Message: " << decrypt << endl;
}
The Caesar Cipher is a simple substitution cipher named after Julius Caesar, who reportedly used it to communicate
with his officials. The technique involves shifting each letter in a message by a fixed number of positions in the
alphabet. For example, with a shift of 3, A would be replaced by D, B would become E, and so on.
The Caesar Cipher is relatively easy to break and is considered to be a very weak form of encryption, but it served its
purpose for Julius Caesar. It's still used for educational and recreational purposes.
Algorithm for Caesar Cipher
Here is a basic algorithm for encoding a message using the Caesar Cipher with a shift of k −
Initialize a variable shift to the value of k.
Iterate through each character c in the message −
If c is a letter (uppercase or lowercase), shift it by shift positions in the alphabet.
To shift an uppercase letter, subtract 'A' from the letter, add the shift value, and take the modulus 26. Then add 'A'
back to get the shifted letter.
To shift a lowercase letter, subtract 'a' from the letter, add the shift value, and take the modulus 26. Then add 'a' back
to get the shifted letter.
b. Append the shifted letter to the encoded message.
Return the encoded message.
To decode an encoded message, the same algorithm can be used with a shift of -k.
Example
def caesar_cipher_encrypt(plaintext, shift):
ciphertext = ""
for c in plaintext:
if c.isalpha():
ascii_code = ord(c)
if c.isupper():
ascii_code = (ascii_code - ord('A') + shift) % 26 + ord('A')
else:
ascii_code = (ascii_code - ord('a') + shift) % 26 + ord('a')
ciphertext += chr(ascii_code)
else:
ciphertext += c
return ciphertext
def caesar_cipher_decrypt(ciphertext, shift):
plaintext = ""
for c in ciphertext:
if c.isalpha():
ascii_code = ord(c)
if c.isupper():
ascii_code = (ascii_code - ord('A') - shift) % 26 + ord('A')
else:
ascii_code = (ascii_code - ord('a') - shift) % 26 + ord('a')
plaintext += chr(ascii_code)
else:
plaintext += c
return plaintext
Please note that this algorithm is limited and can be broken by a cryptanalyst with relative ease. it is not
recommended to use it in any real-world applications, it's commonly used as a learning tool in the field of
cryptography.
Example
Here is an example of encoding and decoding a message using the Caesar Cipher with a shift of 3 −
plaintext = "HELLO WORLD"
shift = 3
ciphertext = caesar_cipher_encrypt(plaintext, shift)
print("Encrypted message:", ciphertext) # Encrypted message: KHOOR ZRUOG

decrypted_text = caesar_cipher_decrypt(ciphertext, shift)


print("Decrypted message:", decrypted_text) # Decrypted message: HELLO WORLD
As you can see, in the first step of the process, the plaintext "HELLO WORLD" is passed to the
caesar_cipher_encrypt function along with the shift value of 3, resulting in the ciphertext "KHOOR ZRUOG".
In the second step, the previously obtained ciphertext is passed to the caesar_cipher_decrypt function along with the
same shift value, and the original plaintext message is obtained.
Example
plaintext = "hello world"
shift = 2
ciphertext = caesar_cipher_encrypt(plaintext, shift)
print("Encrypted message:", ciphertext) # Encrypted message: jgnnq ytqng
decrypted_text = caesar_cipher_decrypt(ciphertext, shift)
print("Decrypted message:", decrypted_text) # Decrypted message: hello world
As you can see, shift of 2 is used for the encryption and the decryption process, resulting in the same plaintext
message "hello world"
Please note that this is just an example, Caesar Cipher is not secure and should not be used in real-world applications.
How to decrypt?
The Caesar Cipher is a simple substitution cipher, so the most straightforward way to decrypt an encoded message
is to try different shift values until the decrypted message makes sense. This is known as a "brute-force" attack.
Here is the basic algorithm for decoding an encoded message using a brute-force attack −
Iterate through all possible shift values, starting from 0 to 25 (since there are 26 letters in the alphabet).
For each shift value, create a new empty string to hold the decoded message.
Iterate through each character c in the encoded message −
If c is a letter (uppercase or lowercase), shift it back by the current shift value positions in the alphabet
To shift an uppercase letter back, subtract the current shift value from the letter, add 26 and take modulus of 26. Then
add 'A' back to get the original letter.
To shift a lowercase letter back, subtract the current shift value from the letter, add 26 and take modulus of 26. Then
add 'a' back to get the original letter.
Append the shifted letter to the decoded message.
Print the decoded message along with the shift value used.
Repeat the process until the message makes sense
It's worth mentioning, that more advanced methods such as frequency analysis, pattern recognition can be used to
break the ciphertext much faster than the brute force method.
It is important to note that the Caesar Cipher is very weak, and is not considered secure for use in modern
cryptography. It's commonly used as a learning tool to introduce the concept of substitution ciphers.
Example
//Simple C++ program to encrypt and decrypt a string
#include <iostream>
using namespace std;
int main()
{
int i, x;
char str[100];//it takes charters up to 100
cout << "Please enter a string:\t";
cin >> str;
cout << "\nPlease choose following options:\n";
cout << "1 = Encrypt the string.\n";
cout << "2 = Decrypt the string.\n";
cin >> x;// accepts characters from users
//using switch case statements
switch(x)
{
//first case for encrypting a string
case 1:
for(i = 0; (i < 100 && str[i] != '\0'); i++)
str[i] = str[i] + 2; //the key for encryption is 3 that is added to ASCII value
cout << "\nEncrypted string: " << str << endl;
break;
//second case for decrypting a string
case 2:
for(i = 0; (i < 100 && str[i] != '\0'); i++)
str[i] = str[i] - 2; //the key for encryption is 3 that is subtracted to ASCII value
cout << "\nDecrypted string: " << str << endl;
break;
default:
cout << "\nInvalid Input !!!\n";
}

return 0;
}
#include <iostream>
using namespace std;

int main()
{
int i, x;
char str[100];

cout << "Please enter a string:\t";


cin >> str;

cout << "\nPlease choose following options:\n";


cout << "1 = Encrypt the string.\n";
cout << "2 = Decrypt the string.\n";
cin >> x;

//using switch case statements


switch(x)
{
//first case for encrypting a string
case 1:
for(i = 0; (i < 100 && str[i] != '\0'); i++)
str[i] = str[i] + 2; //the key for encryption is 3 that is added to ASCII value

cout << "\nEncrypted string: " << str << endl;


break;

//second case for decrypting a string


case 2:
for(i = 0; (i < 100 && str[i] != '\0'); i++)
str[i] = str[i] - 2; //the key for encryption is 3 that is subtracted to ASCII value

cout << "\nDecrypted string: " << str << endl;


break;

default:
cout << "\nInvalid Input !!!\n";
}
return 0;
}
Example
//C++ program for encryption and decryption
#include<iostream>
#include<stdlib.h>
#include<math.h>
#include<string.h>
using namespace std;
int x, y, n, t, i, flag;
long int e[50], d[50], temp[50], j;
char en[50], m[50];
char msg[100];
int prime(long int); //function to check for prime number
void encryption_key();
long int cd(long int);
void encrypt();
void decrypt();
int main()
{
cout << "\nENTER FIRST PRIME NUMBER\n";
cin >> x;
//checking whether input is prime or not
flag = prime(x);
if(flag == 0)
{
cout << "\nINVALID INPUT\n";
exit(0);
}
cout << "\nENTER SECOND PRIME NUMBER\n";
cin >> y;

flag = prime(y);
if(flag == 0 || x == y)
{
cout << "\nINVALID INPUT\n";
exit(0);
}

cout << "\nENTER MESSAGE OR STRING TO ENCRYPT\n";


cin >> msg;

for(i = 0; msg[i] != NULL; i++)


m[i] = msg[i];
n = x * y;
t = (x - 1) * (y - 1);

encryption_key();
cout << "\nPOSSIBLE VALUES OF e AND d ARE\n";

for(i = 0; i < j - 1; i++)


cout << "\n" << e[i] << "\t" << d[i];

encrypt();
decrypt();
return 0;
} //end of the main program

int prime(long int pr)


{
int i;
j = sqrt(pr);
for(i = 2; i <= j; i++)
{
if(pr % i == 0)
return 0;
}
return 1;
}
//function to generate encryption key
void encryption_key()
{
int k;
k = 0;
for(i = 2; i < t; i++)
{
if(t % i == 0)
continue;
flag = prime(i);
if(flag == 1 && i != x && i != y)
{
e[k] = i;
flag = cd(e[k]);
if(flag > 0)
{
d[k] = flag;
k++;
}
if(k == 99)
break;
}
}
}
long int cd(long int a)
{
long int k = 1;
while(1)
{
k = k + t;
if(k % a == 0)
return(k/a);
}
}
//function to encrypt the message
void encrypt()
{
long int pt, ct, key = e[0], k, len;
i = 0;
len = strlen(msg);

while(i != len)
{
pt = m[i];
pt = pt - 96;
k = 1;
for(j = 0; j < key; j++)
{
k = k * pt;
k = k % n;
}
temp[i] = k;
ct= k + 96;
en[i] = ct;
i++;
}
en[i] = -1;
cout << "\n\nTHE ENCRYPTED MESSAGE IS\n";
for(i=0; en[i] != -1; i++)
cout << en[i];
}
//function to decrypt the message
void decrypt()
{
long int pt, ct, key = d[0], k;
i = 0;
while(en[i] != -1)
{
ct = temp[i];
k = 1;
for(j = 0; j < key; j++)
{
k = k * ct;
k = k % n;
}
pt = k + 96;
m[i] = pt;
i++;
}
m[i] = -1;
cout << "\n\nTHE DECRYPTED MESSAGE IS\n";
for(i = 0; m[i] != -1; i++)
cout << m[i];
cout << endl;
}

You might also like