加密过程
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;
}
本文介绍了一种基于Z26的仿射密码体制,详细阐述了加密和解密过程。加密公式为y=k1x+k2(mod26),解密公式为x=_k1(y-k2)(mod26),其中_k1是k1的乘法逆元。通过实例,实现了读取文本文件‘in.txt’进行加密,并将结果保存到‘encode.txt’,同时进行解密,结果保存到‘decode.txt’。
2072

被折叠的 条评论
为什么被折叠?



