Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <algorithm>
- #include <string>
- using namespace std;
- string getInput();
- int gcd(int a, int b);
- void getAB(int & a, int & b);
- bool withinLower(char i);
- bool withinUpper(char i);
- int modInverse(int a);
- void encryptText(string & input, int a, int b);
- void decryptText(string & input, int a, int b);
- int main() {
- string input = getInput();
- int a, b;
- getAB(a, b);
- cout << "\nEncrypted: ";
- encryptText(input, a, b);
- cout << "\n\nDecrypted: ";
- decryptText(input, a, b);
- cout << "\n";
- return 0;
- }
- string getInput() {
- cout << "\nInput string: ";
- string input;
- getline(cin, input);
- return input;
- }
- int gcd(int a, int b) {
- return b == 0 ? a : gcd(b, a % b);
- }
- void getAB(int & a, int & b) {
- do {
- cout << "\na and b must be coprime\na = ";
- cin >> a;
- if (!cin.fail()) {
- cout << "b = ";
- cin >> b;
- }
- cin.clear();
- cin.ignore(numeric_limits<streamsize>::max(), '\n');
- } while (cin.fail() || gcd(a, b) != 1);
- }
- bool withinLower(char i) {
- return i >= 'a' && i <= 'z' ? true : false;
- }
- bool withinUpper(char i) {
- return i >= 'A' && i <= 'Z' ? true : false;
- }
- // from https://rosettacode.org/wiki/Modular_inverse#C.2B.2B
- int modInverse(int a) {
- int b = 26, t, q, x0 = 0, x1 = 1;
- while (a > 1) {
- q = a / b;
- t = b, b = a % b, a = t;
- t = x0, x0 = x1 - q * x0, x1 = t;
- }
- if (x1 < 0) x1 += 26;
- return x1;
- }
- void encryptText(string & input, int a, int b) {
- for (unsigned int i = 0; i < input.length(); ++i) {
- if (withinLower(input[i])) {
- input[i] = (char)((a * (input[i] - 'a') + b) % 26 + 'a');
- }
- else if (withinUpper(input[i])) {
- input[i] = (char)((a * (input[i] - 'A') + b) % 26 + 'A');
- }
- else {
- input[i] = input[i];
- }
- }
- cout << input;
- }
- void decryptText(string & input, int a, int b) {
- for (unsigned int i = 0; i < input.length(); ++i) {
- if (withinLower(input[i])) {
- input[i] = (char)(modInverse(a) * (26 + input[i] - 'a' - b) % 26 + 'a');
- }
- else if (withinUpper(input[i])) {
- input[i] = (char)(modInverse(a) * (26 + input[i] - 'A' - b) % 26 + 'A');
- }
- else {
- input[i] = input[i];
- }
- }
- cout << input;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement