ZBLOG

# write in 2021/7/13 # 自动秘钥密码 DIC = "abcdefghijklmnopqrstuvwxyz" def encrypt_autokey(string, key): ciphertext = "" key += string key_index = 0 for i in string: if i not in DIC: ciphertext += i ciphert...

下面是将您提供的 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;
}

注意事项:

  1. 确保在使用之前对 C++ 编译器环境进行设置。
  2. 字符串处理逻辑与原 Python 代码保持一致,包括非字母字符的处理。
  3. DIC 字符串用于查找字母索引,相应地实现了加密和解密逻辑。


    内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://sdn.0voice.com/?id=6766

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?