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