Created
January 27, 2019 17:42
-
-
Save probablyangg/77f7a5c6105e0d015bc8cce5fcab2fd5 to your computer and use it in GitHub Desktop.
input : text (cipher/plain), key; output : (cipher/plain) text [plaintext: lowercase, ciphertext: UPPERCASE]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
using namespace std; | |
string shift_cipher_encrypt (string plaintext, int shift) { | |
string ciphertext; | |
for (int i = 0; i < plaintext.size(); i ++) { | |
//lower case letters | |
if (plaintext[i] >= 97 && plaintext[i] <= 122) { | |
if ((plaintext[i] + shift) > 122) | |
ciphertext.push_back((((plaintext[i] + shift) % 122) + 96) - 32 ); | |
else | |
ciphertext.push_back((plaintext[i] + shift) - 32); | |
} | |
else if (isdigit(plaintext[i])) ciphertext.push_back(plaintext[i]); | |
} | |
return ciphertext; | |
} | |
string shift_cipher_decrypt (string ciphertext, int shift) { | |
string plaintext; | |
for (int i = 0; i < ciphertext.size(); i ++) { | |
//upper case letters | |
if (ciphertext[i] >= 65 && ciphertext[i] <= 90) { | |
if ((ciphertext[i] - shift) < 65) | |
plaintext.push_back((91 - (65 - (ciphertext[i] - shift))) + 32); | |
else | |
plaintext.push_back ((ciphertext[i] - shift) + 32); | |
} | |
else if (isdigit(ciphertext[i])) plaintext.push_back(ciphertext[i]); | |
} | |
return plaintext; | |
} | |
int main () { | |
string plaintext, ciphertext; | |
int shift, choice; | |
cout << "Enter 1 to Encrypt, 2 to Decrypt: "; | |
cin >> choice; | |
if (choice == 1) { | |
cout << "Enter plaintext: "; | |
cin >> plaintext; | |
cout << "Enter Shift: "; | |
cin >> shift; | |
cout << shift_cipher_encrypt (plaintext, shift) << "\n"; | |
} | |
else if (choice == 2) { | |
cout << "Enter ciphertext: "; | |
cin >> ciphertext; | |
cout << "Enter Shift: "; | |
cin >> shift; | |
cout << shift_cipher_decrypt (ciphertext, shift) << "\n"; | |
} | |
else { | |
cout << "Enter valid choice\n"; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment