Z26上的仿射密碼體制

加密過程
y=k1x+k2(mod26)

解密過程

x=_k1(y-k2)(mod26)

_k1爲k1的乘法逆元,因爲有26這個範圍,而且逆元唯一,所以可直接腦殘試出_k1的值

 

具體實現:

讀文本文件"in.txt"進行加密,結果放到"encode.txt"中,同時進行解密,結果放在"decode.txt"中

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <math.h>
#include <time.h>
using namespace std;

int k1[12]={1,3,5,7,9,11,15,17,19,21,23,25},k2, _k1;
int index;
char temp;
char ans;

int gcd(int a,int b)
{
    int temp;
    if(a<b)
    {
        temp=a;
        a=b;
        b=temp;
    }

    int r=1;
    while(r)
    {
        r=a%b;
        a=b;
        b=r;
    }
    return a;
}

void chengfaniyuan()
{
    int i;
    for(i=1; i<26; i++)
    {
        if((k1[index]*i)%26==1)
        {
            _k1=i;
            return;
        }
    }
}

void encode()
{
    temp=temp-97;
    temp=(k1[index]*temp+k2)%26+97;
}

void decode()
{
    int sum=temp-97-k2;
    while(sum<0)
    {
        sum+=26;
    }
    ans=(_k1*(sum))%26+97;
}

int main()
{
    srand(time(NULL));

    index=rand()%12;
    k2=rand()%26;

    //cout<<k1[index]<<" "<<k2<<endl;
    chengfaniyuan();
    //cout<<_k1<<endl;

//因爲仿射密碼是流密碼,所以對每個字符進行處理
    ifstream in("in.txt");
    ofstream out1("encode.txt");
    ofstream out2("decode.txt");

    while(in.get(temp))
    {
        if(!(temp>='a'&&temp<='z'))
        {
            out1<<temp;
            out2<<temp;
            continue;
        }
        
        encode();
        out1<<temp;
        decode();
        out2<<ans;
    }
    in.close();
    out1.close();
    out2.close();
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章