下面是将您提供的 Python 自动秘钥密码(Autokey Cipher)加密和解密算法转换为 C++ 的代码:
#include <iostream>
#include <string>
const std::string DIC = "abcdefghijklmnopqrstuvwxyz";
std::string encrypt_autokey(const std::string& plaintext, const std::string& key) {
std::string ciphertext;
std::string extended_key = key + plaintext; // 扩展密钥
int key_index = 0;
for (char ch : plaintext) {
if (DIC.find(ch) == std::string::npos) {
ciphertext += ch; // 如果不是字母,直接添加
continue;
}
int char_index = DIC.find(ch);
int key_char_index = DIC.find(extended_key[key_index]);
ciphertext += DIC[(char_index + key_char_index) % 26];
key_index++;
}
return ciphertext;
}
std::string decrypt_autokey(const std::string& ciphertext, const std::string& key) {
std::string plaintext;
std::string current_key = key;
int key_index = 0;
for (char ch : ciphertext) {
if (DIC.find(ch) == std::string::npos) {
plaintext += ch; // 如果不是字母,直接添加
continue;
}
int char_index = DIC.find(ch);
int key_char_index = DIC.find(current_key[key_index]);
char decrypted_char = DIC[(char_index - key_char_index + 26) % 26]; // 加上26以处理负数情况
plaintext += decrypted_char;
current_key += decrypted_char; // 更新当前密钥
key_index++;
}
return plaintext;
}
int main() {
std::string key_ = "linux";
std::string ciphertext_ = encrypt_autokey("autokey", key_);
std::string plaintext_ = decrypt_autokey(ciphertext_, key_);
std::cout << plaintext_ << ": " << ciphertext_ << std::endl;
return 0;
}
注意事项:
- 确保在使用之前对 C++ 编译器环境进行设置。
- 字符串处理逻辑与原 Python 代码保持一致,包括非字母字符的处理。
DIC
字符串用于查找字母索引,相应地实现了加密和解密逻辑。
内容由零声教学AI助手提供,问题来源于学员提问