用c++写一个栅栏密码的加密和解密
时间: 2024-02-20 13:59:16 浏览: 251
C++密码加密与解密
以下是一个 C++ 实现的栅栏密码加密和解密程序:
```cpp
#include <iostream>
#include <string>
using namespace std;
string fence_cipher_encrypt(string plain_text, int rails) {
string fence[rails];
int rail = 0;
int direction = 1;
for (char c : plain_text) {
fence[rail] += c;
rail += direction;
if (rail == 0 || rail == rails - 1) {
direction = -direction;
}
}
string cipher_text;
for (string rail : fence) {
cipher_text += rail;
}
return cipher_text;
}
string fence_cipher_decrypt(string cipher_text, int rails) {
string fence[rails];
int rail = 0;
int direction = 1;
for (char c : cipher_text) {
fence[rail] += '-';
rail += direction;
if (rail == 0 || rail == rails - 1) {
direction = -direction;
}
}
int index = 0;
for (int i = 0; i < rails; i++) {
for (int j = 0; j < fence[i].length(); j++) {
if (fence[i][j] == '-') {
fence[i][j] = cipher_text[index];
index++;
}
}
}
string plain_text;
rail = 0;
direction = 1;
for (int i = 0; i < cipher_text.length(); i++) {
plain_text += fence[rail][0];
fence[rail] = fence[rail].substr(1);
rail += direction;
if (rail == 0 || rail == rails - 1) {
direction = -direction;
}
}
return plain_text;
}
int main() {
string plain_text = "HELLO WORLD";
int rails = 3;
string cipher_text = fence_cipher_encrypt(plain_text, rails);
cout << cipher_text << endl; // HOLELWRDLO
string decrypted_text = fence_cipher_decrypt(cipher_text, rails);
cout << decrypted_text << endl; // HELLO WORLD
return 0;
}
```
使用方式示例:
```cpp
string plain_text = "HELLO WORLD";
int rails = 3;
string cipher_text = fence_cipher_encrypt(plain_text, rails);
cout << cipher_text << endl; // HOLELWRDLO
string decrypted_text = fence_cipher_decrypt(cipher_text, rails);
cout << decrypted_text << endl; // HELLO WORLD
```
其中 `fence_cipher_encrypt` 函数接受两个参数:明文 `plain_text` 和栅栏数量 `rails`,返回加密后的密文。`fence_cipher_decrypt` 函数接受两个参数:密文 `cipher_text` 和栅栏数量 `rails`,返回解密后的明文。
阅读全文