使用c++中string类,相比于使用数组,没有了数组长度的限制,而且操作跟加的方便
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
|
#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;
}
|
本文转自 nw01f 51CTO博客,原文链接:http://blog.51cto.com/dearch/1750314,如需转载请自行联系原作者