C++程序实现维吉尼亚密码
维吉尼亚密码是一种用于加密字母文本的多表代换方法。
维吉尼亚密码表用于此方法中的加密和解密,其中字母 A 到 Z 写在 26 行中。

加密
密钥:WELCOME
消息:Thisistutorialspoint
这里我们需要通过重复给定的密钥,直到其长度等于原始消息长度来获得一个密钥。
对于加密,取消息和密钥的第一个字母,即 T 和 W。在维吉尼亚密码表中找到 T 行和 W 列相交的字母,即 P。
对消息文本中所有剩余的字母重复相同的过程。
最终,加密后的消息文本为:
加密后的消息:PLTUWEXQXZTWMPOTZKBF。
密文可以通过以下公式生成。
Ei = (Pi + Ki) mod 26
这里 P 是明文,K 是密钥。
解密
密钥:WELCOME
加密后的消息:PLTUWEXQXZTWMPOTZKBF
取生成的密钥和加密消息的第一个字母,即 P 和 W。分析维吉尼亚密码表,在 W 列中查找字母 P,对应的行将是原始消息的第一个字母,即 T。
对加密消息中的所有字母重复此过程。
原始消息:Thisistutorialspoint
这可以用以下公式表示成代数形式。
Pi = (Ei – Ki + 26) mod 26
这是一个实现维吉尼亚密码的 C++ 程序。
算法
Begin Function encryption(string t) for i = 0, j = 0 to t.length() - 1 char c = t[i] if (c >= 'a' and c <= 'z') c = c + 'A' - 'a' else if (c < 'A' or c > 'Z') continue output = output + (c + k[j] ) % 26 + 'A' j = (j + 1) % k.length() return output End Begin Function decryption(string t) for i = 0, j = 0 to t.length() - 1 char c = t[i] if (c >= 'a' and c <= 'z') c = c + 'A' - 'a' else if (c < 'A' or c > 'Z') continue output =output + (c - k[j] + 26) % 26 + 'A' j = (j + 1) % k.length() return output End
示例
#include <iostream>
#include <string>
using namespace std;
class Vig {
public:
string k;
Vig(string k) {
for (int i = 0; i < k.size(); ++i) {
if (k[i] >= 'A' && k[i] <= 'Z')
this->k += k[i];
else if (k[i] >= 'a' && k[i] <= 'z')
this->k += k[i] + 'A' - 'a';
}
}
string encryption(string t) {
string output;
for (int i = 0, j = 0; i < t.length(); ++i) {
char c = t[i];
if (c >= 'a' && c <= 'z')
c += 'A' - 'a';
else if (c < 'A' || c > 'Z')
continue;
output += (c + k[j] - 2 * 'A') % 26 + 'A'; //added 'A' to bring it in range of ASCII alphabet [ 65-90 | A-Z ]
j = (j + 1) % k.length();
}
return output;
}
string decryption(string t) {
string output;
for (int i = 0, j = 0; i < t.length(); ++i) {
char c = t[i];
if (c >= 'a' && c <= 'z')
c += 'A' - 'a';
else if (c < 'A' || c > 'Z')
continue;
output += (c - k[j] + 26) % 26 + 'A';//added 'A' to bring it in range of ASCII alphabet [ 65-90 | A-Z ]
j = (j + 1) % k.length();
}
return output;
}
};
int main() {
Vig v("WELCOME");
string ori ="Thisistutorialspoint";
string encrypt = v.encryption(ori);
string decrypt = v.decryption(encrypt);
cout << "Original Message: "<<ori<< endl;
cout << "Encrypted Message: " << encrypt << endl;
cout << "Decrypted Message: " << decrypt << endl;
}输出
Original Message: Thisistutorialspoint Encrypted Message: PLTUWEXQXZTWMPOTZKBF Decrypted Message: THISISTUTORIALSPOINT
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP