使用c++中string类,相比于使用数组,没有了数组长度的限制,而且操作跟加的方便
#include <iostream>
#include <string>
using namespace std;
string jiami(string str,int k,int b);
string jiemi(string pass,int k,int b);
int canshu(int k,int b);
int main()
{
string str; //明文
string pass; //密文
string res; //明文
int k,b; //加密算法的参数
cout<<"请输入明文:";
cin>>str;
cout<<"请输入加密算法的参数(k b):";
cin>>k>>b;
while(!canshu(k,b))
{
cout<<"参数不合法(参数应该与mod·26互为素数),请重新输入:";
cin>>k>>b;
}
cout<<"加密函数为:f(x)="<<k<<"x+"<<b<<endl;
pass=jiami(str,k,b);
cout<<"密文为:"<<pass<<endl;
res=jiemi(pass,k,b);
cout<<"解密后明文为:"<<res<<endl;
return 0;
}
int canshu(int k,int b)
{
int c,t,mod = 26; //模 26
if(k==1 || k%2==0)
return 0;
if(mod<k)
{
t=mod;
mod=k;
k=t;
}
while(c!=0)
{
c=mod%k;
mod=k;
k=c;
}
if(mod==1)
return 1;
else
return 0;
}
string jiami(string str,int k,int b)
{
int i;
cout<<"\n输入的需要加密的明文为:"<<str<<endl;
for(i=0;i<str.length();i++)
{
int a;
a=(str[i]-97)*k+b; //加密
if(a>25) //对照为0-25 mod为26
{
do //保证不超出域
{
a=a-26;
}while(a>25);
a=a+97; //加密后得到的ASC码;
str[i]=(char)a;
}
else
{
a=a+97;
str[i]=(char)a;
}
}
return str;
}
string jiemi(string pass,int k,int b)
{
int i;
for(i=0;i<pass.length();i++) //解密过程
{
int d;
d=(pass[i]-97)-b;
while(d%k!=0)
{
d=d+26;
}
d=d/k;
pass[i]=(char)(d+97);
}
return pass;
}本文出自 “启思·朝圣者” 博客,请务必保留此出处http://dearch.blog.51cto.com/10423918/1750314
简单的加密与解密的实现---仿射密码(c++使用string)
原文:http://dearch.blog.51cto.com/10423918/1750314