-
-
[旧帖] [原创]一个上机作业 PlayFair加密 0.00雪花
-
发表于: 2011-4-2 19:53 1896
-
#include <iostream>
#include <string>
#include <algorithm>
#include <stdlib.h>
using namespace std;
class Unique{
string s;
public:
string get() {return s; }
string operator()(char c)
{
if(s.end() == find(s.begin(), s.end(), c))
s += c;
return s;
}
};
string myUnique(string& in)
{
return
for_each(in.begin(), in.end(), Unique()).get();
}
int main()
{
string s ;
cout<<"请输入密钥(仅限英文字母,切勿空格):" ;
cin>>s ;
string alphabet(26, 'A') ;
for (int i = 0, char c = 65 ; i != alphabet.size() ; ++i, ++c)
{
alphabet[i] = c ;
}
s += alphabet ; //将输入的密钥加上字母表
for (string::size_type ind = 0 ; ind != s.size() ; ++ind) //将整个字符串转化为大写,并改'J'为'I'
{
s[ind] = toupper(s[ind]) ;
if (s[ind] == 'J')
{
s[ind] = 'I' ;
}
}
string str = myUnique(s) ; //去掉重复字母
cout<<"密钥矩阵为:"<<endl ;
for (i = 0 ; i != str.size() ; ++i)
{
cout<<str[i]<<" " ;
if((i + 1) % 5 == 0)
{
cout<<endl ;
}
}
char matrix[5][5] = {'A'} ;
int m = 0, n = 0, k = 0 ;
for (m = 0 ; m < 5 ; m++)
{
for (n = 0 ; n < 5 ; n++)
{
matrix[m][n] = str[k++] ;
}
}
string plain ;
cout<<"请输入明文(仅限英文字母,切勿空格):" ;
cin>>plain ;
int size = plain.size() ;
for (string ::size_type ii = 0 ; ii < size - 1 ; ii += 2) //修改明文,使之规范化
{
if (plain[ii] == plain[ii + 1])
{
plain.insert(ii + 1, 1, 'x') ; //两个字符相同,添加X
size = plain.size() - 1 ;
}
}
if (plain.size() % 2 != 0) //使字符成为偶数
{
plain += 'x' ;
}
int i1, j1, i2, j2 ;
for (int index = 0 ; index < plain.size() - 1 ; index += 2)
{
for (m = 0 ; m < 5 ; m++)
{
for (n = 0 ; n < 5 ; n++)
{
if (toupper(plain[index]) == matrix[m][n])
{
i1 = m ;
j1 = n ;
}
if (toupper(plain[index + 1]) == matrix[m][n])
{
i2 = m ;
j2 = n ;
}
}
}
if (i1 == i2)
{
plain[index] = matrix[i1][(j1 + 1) % 5] ;
plain[index + 1] = matrix[i1][(j2 + 1) % 5] ;
}
if (j1 == j2)
{
plain[index] = matrix[(i1 + 1) % 5][j1] ;
plain[index + 1] = matrix[(i2 + 1) % 5][j1] ;
}
if (i1 != i2 && j1 != j2)
{
plain[index] = matrix[i1][j2] ;
plain[index + 1] = matrix[i2][j1] ;
}
}
cout<<"密文为:"<<plain<<endl ;
system("pause") ;
return 0 ;
}
[注意]传递专业知识、拓宽行业人脉——看雪讲师团队等你加入!
赞赏
- Dll基地址问题 1623
- 有谁用过UEStudio? 4006
- [求助]怎么手动链接.obj文件和.res文件 6439
- [求助]有没有支持像vc中Visual Assist X的win32汇编IDE的插件 3333
- [原创]一个上机作业 PlayFair加密 1897