Vigenere Cipher C++ Program - The Coding Shala

Home >> Computer Network >> Vigenere Cipher

Vigenere Cipher C++ Program

Here is the C++ Program to Implement the Vigenere Cypher.

C++ Code: 

#include<bits/stdc++.h>

using namespace std;
void encrypt(string key){
 char ch;
 FILE *fp1, *fp2;
 
 fp1 = fopen("encript.txt","r");
 fp2 = fopen("decript.txt","w");
 
 int i=0;
 
 do{
  if(i==key.size()-1){
   i=0;
  }
  ch = fgetc(fp1);
  if(isalpha(ch)){
   ch = ((ch-'a' + key[i]-'a')%26)+'a';
   cout << ch;
   fputc(ch,fp2);
   i++;
  }
 }while(ch!=EOF);
 fclose(fp1);
 fclose(fp2);
}

void decrypt(string key){
 char ch;
 FILE *fp1, *fp2;
 int k;
 fp1 = fopen("decript.txt","r");
 fp2 = fopen("encript.txt","w");
 int i=0;
 do{
  if(i==key.size()-1){
   i=0;
  }
  ch=fgetc(fp1);
  k=key[i]-'a';
  k=26-k;
  if(isalpha(ch)){
    ch=((ch-'a'+k)%26)+'a';
    cout << ch;
    fputc(ch,fp2);
    i++;
  }
 }while(ch!=EOF);
 fclose(fp1);
 fclose(fp2);
}

int main(){
 int ch;
 string key;
 start:
  cout<<"This is vignere cipher\n Enter choice\n";
 cout <<  "1.encrypt\n  2.decrypt\n 3.exit\n";
 cin >> ch;
 switch(ch){
  case 1:
   cout << "enter key  :\n";
   cin >> key;
   encrypt(key);
   goto start;
   break;
  case 2:
   cout << "enter key  :\n";
   cin >> key;
   decrypt(key);
   goto start;
   break;
  case 3:
   exit(0);
 }
 
 
 return 0;
}


Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to Create a Simple Calculator - The Coding Shala

New Year Chaos Solution - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Single Number 2 LeetCode Solution - The Coding Shala