Encryption and Decryption in C++

Encryption and Decryption text in C++ programming are used to encrypt any text by using a user-provided key and decrypt text by using the user-provided key.

Program Password Encryption and Decryption

Program

#include<iostream.h>
#include<conio.h>
#include<string.h> //including Library for working with String.
void encrypt(char password[],int key) //this is parameterized function.
{
    unsigned int i;
    for(i = 0; i < strlen(password); ++i)
    {
        password[i] = password[i] - key;
    }
}
void decrypt(char password[],int key) //this is parameterized function.
{
    unsigned int i;
    for(i = 0; i < strlen(password); ++i)
    {
        password[i] = password[i] + key;
    }
}
void main()
{
 char password[20] ;
    cout<<"Enter the password:  ";
    cin>>password;
    cout<<"Password  =  "<<password<<endl;
    encrypt(password,0xFACA); //passing arguments.
    cout<<"Encrypted value  =  "<<password<<endl;
    decrypt(password,0xFACA); //passing arguments.
    cout<<"Decrypted value  =  "<<password<<endl;
 getch();
}
Output
Enter your name:
Bilal
Name = Bilal
Encrypted name = xƒóùó
Decrypted name = Bilal

Program Encrypting Text of Text File

Program

#include<iostream.h>
#include<conio.h>
#include<stdio.h>
void fun();
void main()
{
fun();
getch();
}
void fun()
{
FILE *fs, *ft;
char ch;
cout<<"Reading MyTxtFile.txt"<<endl;
fs = fopen("C://test/MyTxtFile.txt", "r"); //normal file.
cout<<"Writing MyTxtFile2.txt"<<endl;
ft = fopen("C://test/MyTxtFile2.txt", "w"); //encrypted file.
if(fs == NULL || ft == NULL)
{
cout<<"File opening error!";
}
cout<<"Encrypting MyTxtFile2.txt"<<endl;
while((ch = getc(fs)) != EOF)
putc(~ch, ft);
fclose(fs);
fclose(ft);
cout<<"Process finished";
}
Output
Reading MyTxtFile.txt
Writing MyTxtFile2.txt
Encrypting MyTxtFile2.txt
Process finished