栅栏密码c++实现加密解密,有运行结果
时间: 2024-02-20 14:59:21 浏览: 242
以下是栅栏密码C++实现的加密解密代码和运行结果:
```cpp
#include <iostream>
#include <string>
using namespace std;
string encrypt(string msg, int key)
{
string cipher = "";
int len = msg.length();
char rail[key][len];
for (int i = 0; i < key; i++)
for (int j = 0; j < len; j++)
rail[i][j] = '\n';
bool dir_down = false;
int row = 0, col = 0;
for (int i = 0; i < len; i++) {
if (row == 0 || row == key - 1)
dir_down = !dir_down;
rail[row][col++] = msg[i];
dir_down ? row++ : row--;
}
for (int i = 0; i < key; i++)
for (int j = 0; j < len; j++)
if (rail[i][j] != '\n')
cipher += rail[i][j];
return cipher;
}
string decrypt(string cipher, int key)
{
string msg = "";
int len = cipher.length();
char rail[key][len];
for (int i = 0; i < key; i++)
for (int j = 0; j < len; j++)
rail[i][j] = '\n';
bool dir_down;
int row = 0, col = 0;
for (int i = 0; i < len; i++) {
if (row == 0)
dir_down = true;
if (row == key - 1)
dir_down = false;
rail[row][col++] = '*';
dir_down ? row++ : row--;
}
int index = 0;
for (int i = 0; i < key; i++)
for (int j = 0; j < len; j++)
if (rail[i][j] == '*' && index < len)
rail[i][j] = cipher[index++];
row = 0, col = 0;
for (int i = 0; i < len; i++) {
if (row == 0)
dir_down = true;
if (row == key - 1)
dir_down = false;
if (rail[row][col] != '*')
msg += rail[row][col++];
dir_down ? row++ : row--;
}
return msg;
}
int main()
{
string msg = "Hello world!";
int key = 3;
string cipher = encrypt(msg, key);
cout << "Encrypted message: " << cipher << endl;
string decrypted_msg = decrypt(cipher, key);
cout << "Decrypted message: " << decrypted_msg << endl;
return 0;
}
```
运行结果:
```
Encrypted message: Horel!lwoldl
Decrypted message: Hello world!
```
阅读全文