Saturday, July 27, 2013

Affine Cipher Encryption and Decryption

//Affine Cipher
#include <iostream>
#include <cstdio>
#include <string>
using namespace std;

int multiplicative_inverse(int, int);

int main()
{
    int key_1, key_2, x;
    string plainText, cipherText;
    while(cin>>plainText>>key_1>>key_2){
        //encryption
        cipherText = "";
        int len = plainText.size();
        for(int i=0; i<len; i++){
            x = ((plainText[i] - 'a') * key_1 + key_2) % 26;
            cipherText += x + 'A';
        }
        cout<<"Cipher Text: "<<cipherText<<endl;

        //decryption
        plainText = "";
        int keyInverse = multiplicative_inverse(26, key_1);
        cout<<"Multiplicative Inverse: "<<keyInverse<<endl;
        for(int i=0; i<len; i++){
            x = ((cipherText[i] - 'A' - key_2) * keyInverse) % 26;
            if(x < 0) x += 26;
            plainText += x + 'a';
        }
        cout<<"Plain Text: "<<plainText<<endl;

    }
    return 0;
}

int multiplicative_inverse(int x, int y){
    int q, r, r1, r2, t1, t2, t;
    r1 = x;
    r2 = y;
    t1 = 0;
    t2 = 1;
    while(r2 != 0){
        q = r1 / r2;
        r = r1 % r2;
        t = t1 - t2*q;
        r1 = r2;
        r2 = r;
        t1 = t2;
        t2 = t;
    }
    if(r1 != 1) return 0;
    else {
        if(t1<0) return t1+x;
        else return t1;
    }
}

No comments:

Post a Comment