Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Program for Encryption/Decryption in Vigenere Cipher
- © Copyright 2020 Iwo Strzeboński
- Published under WTFPLv2
- Language: C++
- */
- /*
- Files:
- vigenere.key: file with encryption.decryption key
- message.txt: file with message to be encrypted
- message.enc: file with message to be decrypted (known also as cryptograph)
- */
- #include <iostream>
- #include <fstream>
- #include <string>
- using namespace std;
- string * generate_tabula_recta(string alph) {
- int n = alph.length();
- string * arr = new string[n];
- for (int i = 0; i < n; i++) {
- arr[i] = alph.substr(i, n) + alph.substr(0, i);
- }
- return arr;
- }
- string decode_vigenere(string crypt, string alph, string arr[], string key) {
- string mess = "";
- int i = 0, n = 0;
- for (int a = 0; a < crypt.length(); a++) {
- n = n > key.length() - 1 ? 0 : n;
- i = alph.find(key[n]);
- for (int b = 0; b < alph.length(); b++) {
- if (arr[b][i] == crypt[a]) {
- mess += arr[b][0];
- break;
- }
- }
- n++;
- }
- return mess;
- }
- string encode_vigenere(string mess, string alph, string arr[], string key) {
- string crypt = "";
- int i = 0, n = 0;
- for (int a = 0; a < mess.length(); a++) {
- n = n > key.length() - 1 ? 0 : n;
- i = alph.find(key[n]);
- for (int b = 0; b < alph.length(); b++) {
- if (arr[b][0] == mess[a]) {
- crypt += arr[b][i];
- break;
- }
- }
- n++;
- }
- return crypt;
- }
- int main() {
- ifstream keyfile ("vigenere.key");
- string alphabet = "";
- for(int a = 0; a < 128; a++) {
- if(isprint(a)) alphabet += a;
- }
- string * arr;
- string array[alphabet.length()];
- arr = generate_tabula_recta(alphabet);
- for (int i = 0; i < alphabet.length(); i++) {
- array[i] = * (arr + i);
- }
- delete[] arr;
- string mode = "", key = "", cryptograph = "", message = "";
- getline(keyfile, key, (char)keyfile.eof());
- while (true) {
- cout << "[D]ecode or [E]ncode? ";
- getline(cin, mode);
- if (mode == "D") {
- ifstream cryptographfile ("message.enc");
- ofstream messagefile ("message.txt");
- getline(cryptographfile, cryptograph, (char)cryptographfile.eof());
- messagefile << decode_vigenere(cryptograph, alphabet, array, key);
- break;
- } else if (mode == "E") {
- ifstream messagefile ("message.txt");
- ofstream cryptographfile ("message.enc");
- getline(messagefile, message, (char)messagefile.eof());
- cryptographfile << encode_vigenere(message, alphabet, array, key);
- break;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement