c++完成栅栏密码加密
时间: 2024-09-06 12:04:12 浏览: 17
C++中实现栅栏密码(Fence Pattern Encryption)是一种简单的位操作加密技术,它通过将明文按一定规则排列成矩阵,再逐行或逐列读取密文。下面是一个简单的例子,假设我们有四个字符,使用2x2的栅栏模式:
```cpp
#include <iostream>
#include <string>
std::string fencePatternEncrypt(const std::string& plaintext, int rows, int cols) {
if (plaintext.empty() || rows * cols < plaintext.size()) {
return "Invalid input";
}
std::string ciphertext = "";
for (int i = 0; i < plaintext.size(); ++i) {
ciphertext += plaintext[i];
if ((i + 1) % rows == 0) { // 当行数达到时,换列
ciphertext += plaintext[i + rows]; // 从下一行取下一个字符
}
}
return ciphertext;
}
int main() {
std::string plaintext = "Hello, World!";
int rows = 2, cols = 2;
std::string encrypted_text = fencePatternEncrypt(plaintext, rows, cols);
std::cout << "Encrypted text: " << encrypted_text << std::endl;
return 0;
}
```
在这个示例中,`fencePatternEncrypt`函数接受一个字符串、行数和列数作为参数,然后按照栅栏模式加密文本。运行这个程序,你会发现每个字符都和相邻的字符交替出现。