#include <iostream>
#include <string>
#include <string.h>
#pragma warning(disable:4996)
/*
* @Author:timerring
* @Date: 2021-10-20 14:05:49
* @LastEditTime: 2021-10-22 08:11:15
* @FilePath:c:\Users\timerring\Vigenere.cpp
*/
using namespace std;
const int N = 26;
//定义二维密码表
char v[N][N] = { {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'} };
int number(char x)
{//把行号字母对应到数字空间上
char y = 'a';
for (int i = 0; i < N; i++)
{
if (x == (y + i)) return i;
}
}
void encryption(string msg, string key)
{//定义加密过程
cout << "plaintext:";
cin >> msg;
cout << "key:";
cin >> key;
int mlen, klen;
//获取明文和密钥的长度
mlen = msg.length();
klen = key.length();
char* p, * q, * t;//明文,初始密钥,密钥串
//把string换成char
p = new char[msg.length() + 1];
//用strcpy函数进行对应的复制
strcpy(p, msg.c_str());
q = new char[key.length() + 1];
strcpy(q, key.c_str());
t = new char[msg.length() + 1];
int j = 0;
for (int i = 0; i < mlen; i++)
{
t[i] = q[j];
j++;
j = j % klen;
}
cout << "ciphertext:";
for (int i = 0; i < mlen; i++)
//按位输出密文字符
cout << v[number(t[i])][number(p[i])];
cout << endl;
}
void decryption(string c, string key)
{//定义解密过程
cout << "ciphertext:";
cin >> c;
cout << "key:";
cin >> key;
int clen, klen;
clen = c.length();
klen = key.length();
char* p, * q, * t;//密文,初始密钥,密钥串
//将string换成char
p = new char[c.length() + 1];
//用strcpy函数进行对应的复制
strcpy(p, c.c_str());
q = new char[key.length() + 1];
strcpy(q, key.c_str());
t = new char[c.length() + 1];
int j = 0;
for (int i = 0; i < clen; i++)
{
t[i] = q[j];
j++;
j = j % klen;
}//生成密钥
cout << "plaintext:";
for (int i = 0; i < clen; i++)
for (int j = 0; j < N; j++)
if (v[number(t[i])][j] == p[i]) { cout << char(j + 97); break; }
cout << endl;
}
int main()
{
for (int i = 1; i < N; i++)
{
for (int j = 0; j < N; j++)
{
v[i][j] = v[i - 1][(j + 1) % N];
}//将方阵进行初始化
}
cout << "You are welcome to use Vigenere in SDU\n" << endl;
cout << "Please enter the corresponding operation number:" << endl;
int flag;
do {
cout << "1.Encrypt\n2.Decrypt\n";
cin >> flag;
string m, key;
if (flag == 1)encryption(m, key);
else if (flag == 2) decryption(m, key);
else
break;
} while (flag != 3);
return 0;
}
评论0