跳到正文

个人记录

GFDMC1.0.0

cornyumi约 25 分钟
原文

这是 2025年11月18日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2025年11月18日
收录
2025年12月12日
更新
2026年11月14日
篇幅
约 25 分钟

版本

  1. v2当前
  2. v1

主程序

C++
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <ctime>
#include <cstdlib>
#include <sstream>
#include <cctype>
#include <set>

class GaloisCipher {
private:
    static const unsigned long PRIME;
    std::string master_key;

    long extended_gcd(long a, long b, long& x, long& y) {
        if (a == 0) {
            x = 0;
            y = 1;
            return b;
        }
        long x1, y1;
        long gcd = extended_gcd(b % a, a, x1, y1);
        x = y1 - (b / a) * x1;
        y = x1;
        return gcd;
    }

    long mod_inverse(long a, long m) {
        long x, y;
        long gcd = extended_gcd(a % m, m, x, y);
        if (gcd != 1) return -1;
        // 确保返回的逆元是正数
        long result = (x % m + m) % m;
        return result;
    }

    unsigned long simple_hash(const std::string& str) {
        unsigned long hash = 5381;
        for (std::string::const_iterator it = str.begin(); it != str.end(); ++it) {
            hash = ((hash << 5) + hash) + static_cast<unsigned char>(*it);
        }
        return hash;
    }

    std::string to_hex(long num) {
        std::stringstream ss;
        ss << std::hex << num;
        std::string result = ss.str();
        std::transform(result.begin(), result.end(), result.begin(), ::tolower);
        return result;
    }

    long from_hex(const std::string& hex) {
        long num;
        std::stringstream ss;
        ss << std::hex << hex;
        ss >> num;
        return num;
    }

    unsigned short crc16(const std::string& data) {
        unsigned short crc = 0xFFFF;
        for (std::string::const_iterator it = data.begin(); it != data.end(); ++it) {
            crc ^= static_cast<unsigned short>(static_cast<unsigned char>(*it)) << 8;
            for (int i = 0; i < 8; i++) {
                crc = (crc & 0x8000) ? ((crc << 1) ^ 0x1021) : (crc << 1);
            }
        }
        return crc & 0xFFFF;
    }

    std::vector<long> generate_domain_pool() {
        std::vector<long> pool;
        for (long i = 1; i < PRIME; i++) {
            pool.push_back(i);
        }
        return pool;
    }

    int string_to_int(const std::string& s) {
        std::stringstream ss(s);
        int n;
        ss >> n;
        return n;
    }
    
    std::vector<long> generate_key_sequence() const {
        std::vector<long> key_seq;
        for (std::string::const_iterator it = master_key.begin(); it != master_key.end(); ++it) {
            long char_val = static_cast<long>(static_cast<unsigned char>(*it));
            long key_val = ((char_val * 31) % (PRIME - 1)) + 1;
            key_seq.push_back(key_val);
        }
        if (key_seq.empty()) {
            key_seq.push_back(1);
        }
        return key_seq;
    }

    // 安全的模运算,处理大数乘法
    long safe_mod_mul(long a, long b, long m) {
        // 防止乘法溢出
        long result = 0;
        a = a % m;
        while (b > 0) {
            if (b % 2 == 1) {
                result = (result + a) % m;
            }
            a = (a * 2) % m;
            b /= 2;
        }
        return result % m;
    }

    long safe_mod(long a, long m) {
        long result = a % m;
        if (result < 0) {
            result += m;
        }
        return result;
    }

public:
    GaloisCipher(const std::string& key) : master_key(key) {}

    std::string encrypt(const std::string& plaintext, const std::string& salt = "") {
        if (plaintext.empty() || master_key.empty()) return "";

        std::set<char> char_set;
        for (std::string::const_iterator it = plaintext.begin(); it != plaintext.end(); ++it) {
            char_set.insert(*it);
        }
        std::vector<char> all_chars(char_set.begin(), char_set.end());
        int char_count = all_chars.size();

        std::vector<long> domain_pool = generate_domain_pool();
        unsigned long seed = simple_hash(master_key + salt);
        srand(static_cast<unsigned int>(seed));
        std::random_shuffle(domain_pool.begin(), domain_pool.end());

        std::map<char, long> char_to_domain;
        std::map<long, char> domain_to_char;
        for (int i = 0; i < char_count; i++) {
            char c = all_chars[i];
            long domain_val = domain_pool[i];
            char_to_domain[c] = domain_val;
            domain_to_char[domain_val] = c;
        }

        std::vector<long> key_seq = generate_key_sequence();
        int key_len = key_seq.size();

        std::vector<long> cipher_nums;
        long prev_cipher = 0;
        int key_idx = 0;

        for (std::string::const_iterator it = plaintext.begin(); it != plaintext.end(); ++it) {
            char c = *it;
            long P = char_to_domain[c];
            long K = key_seq[key_idx];
            
            // 使用安全的模乘法
            long product = safe_mod_mul(P, K, PRIME);
            long C = safe_mod(product + prev_cipher, PRIME);
            
            cipher_nums.push_back(C);
            prev_cipher = C;
            key_idx = (key_idx + 1) % key_len;
        }

        std::ostringstream packet;
        for (size_t i = 0; i < cipher_nums.size(); i++) {
            if (i > 0) packet << ",";
            packet << to_hex(cipher_nums[i]);
        }

        packet << "|";
        bool first_map = true;
        for (std::map<char, long>::const_iterator it = char_to_domain.begin(); it != char_to_domain.end(); ++it) {
            if (!first_map) packet << ",";
            packet << static_cast<int>(it->first) << "=" << to_hex(it->second);
            first_map = false;
        }

        std::string data_for_crc = packet.str();
        unsigned short crc = crc16(data_for_crc);
        packet << "|" << to_hex(crc);

        return packet.str();
    }

    std::string decrypt(const std::string& data_packet) {
        if (data_packet.empty() || master_key.empty()) {
            return "错误:输入数据或密钥为空";
        }

        try {
            size_t pos1 = data_packet.find('|');
            size_t pos2 = data_packet.find('|', pos1 + 1);
            if (pos1 == std::string::npos || pos2 == std::string::npos) {
                return "错误:数据包格式无效";
            }

            std::string cipher_part = data_packet.substr(0, pos1);
            std::string mapping_part = data_packet.substr(pos1 + 1, pos2 - pos1 - 1);
            std::string crc_part = data_packet.substr(pos2 + 1);

            std::string data_for_crc = cipher_part + "|" + mapping_part;
            unsigned short calc_crc = crc16(data_for_crc);
            unsigned short stored_crc = from_hex(crc_part);
            if (calc_crc != stored_crc) {
                std::cerr << "警告:数据包校验失败,可能已被篡改!" << std::endl;
            }

            std::vector<long> cipher_nums;
            std::stringstream cipher_stream(cipher_part);
            std::string hex_str;
            while (std::getline(cipher_stream, hex_str, ',')) {
                if (!hex_str.empty()) {
                    cipher_nums.push_back(from_hex(hex_str));
                }
            }
            if (cipher_nums.empty()) {
                return "错误:密文数据为空";
            }

            std::map<long, char> domain_to_char;
            std::stringstream mapping_stream(mapping_part);
            std::string map_pair;
            while (std::getline(mapping_stream, map_pair, ',')) {
                size_t eq_pos = map_pair.find('=');
                if (eq_pos == std::string::npos) continue;

                int char_ascii = string_to_int(map_pair.substr(0, eq_pos));
                long domain_val = from_hex(map_pair.substr(eq_pos + 1));
                domain_to_char[domain_val] = static_cast<char>(char_ascii);
            }
            if (domain_to_char.empty()) {
                return "错误:映射表解析失败";
            }

            std::vector<long> key_seq = generate_key_sequence();
            int key_len = key_seq.size();

            std::string plaintext;
            long prev_cipher = 0;
            int key_idx = 0;
            int error_count = 0;

            for (std::vector<long>::const_iterator it = cipher_nums.begin(); it != cipher_nums.end(); ++it) {
                long C = *it;
                long K = key_seq[key_idx];
                long K_inv = mod_inverse(K, PRIME);

                if (K_inv == -1) {
                    plaintext += '?';
                    error_count++;
                } else {
                    // 修复解密计算:分步进行,避免溢出
                    long temp = safe_mod(C - prev_cipher, PRIME);
                    // 使用安全的模乘法
                    long P = safe_mod_mul(temp, K_inv, PRIME);

                    // 调试输出(可选)
                    // std::cout << "C=" << C << ", K=" << K << ", K_inv=" << K_inv 
                    //           << ", temp=" << temp << ", P=" << P << std::endl;

                    if (domain_to_char.find(P) != domain_to_char.end()) {
                        plaintext += domain_to_char[P];
                    } else {
                        plaintext += '?';
                        error_count++;
                        // 调试输出
                        std::cerr << "无法找到域值 " << P << " 对应的字符" << std::endl;
                    }
                }

                prev_cipher = C;
                key_idx = (key_idx + 1) % key_len;
            }

            if (error_count > 0) {
                std::cerr << "警告:解密过程中发现 " << error_count << " 个错误字符(已用「?」标记)" << std::endl;
            }

            return plaintext;

        } catch (const std::exception& e) {
            return "解密错误:" + std::string(e.what());
        }
    }
};

const unsigned long GaloisCipher::PRIME = 65537;

int main() {
    std::cout << "=== 伽罗瓦域动态映射加密系统(GFDMC)- C++98 最终稳定版 ===" << std::endl;

    while (true) {
        std::cout << "\n选择模式: 1=加密, 2=解密, 0=退出" << std::endl;
        std::cout << "请输入选择: ";
        int choice;
        std::cin >> choice;
        std::cin.ignore();

        if (choice == 0) {
            std::cout << "感谢使用!" << std::endl;
            break;
        } else if (choice == 1) {
            std::cout << "请输入明文: ";
            std::string plaintext;
            std::getline(std::cin, plaintext);

            std::cout << "请输入密钥: ";
            std::string key;
            std::getline(std::cin, key);

            std::cout << "请输入盐值(可选,直接回车跳过): ";
            std::string salt;
            std::getline(std::cin, salt);

            GaloisCipher cipher(key);
            std::string packet = cipher.encrypt(plaintext, salt);

            if (!packet.empty()) {
                std::cout << "\n加密成功!" << std::endl;
                std::cout << "原始明文: " << plaintext << std::endl;
                std::cout << "加密数据包: " << packet << std::endl;

                std::cout << "\n立即验证解密..." << std::endl;
                std::string decrypted = cipher.decrypt(packet);
                std::cout << "解密结果: " << decrypted << std::endl;

                if (decrypted == plaintext) {
                    std::cout << "加解密验证成功!" << std::endl;
                } else {
                    std::cout << "加解密验证失败!" << std::endl;
                    // 显示差异
                    std::cout << "差异位置: ";
                    for (size_t i = 0; i < plaintext.size() && i < decrypted.size(); i++) {
                        if (plaintext[i] != decrypted[i]) {
                            std::cout << "位置" << i << "('" << plaintext[i] << "'->'" << decrypted[i] << "') ";
                        }
                    }
                    std::cout << std::endl;
                }
            } else {
                std::cerr << "加密失败(明文或密钥为空)" << std::endl;
            }

        } else if (choice == 2) {
            std::cout << "请输入加密数据包: ";
            std::string packet;
            std::getline(std::cin, packet);

            std::cout << "请输入密钥: ";
            std::string key;
            std::getline(std::cin, key);

            GaloisCipher cipher(key);
            std::string plaintext = cipher.decrypt(packet);

            if (plaintext.find("错误") == std::string::npos) {
                std::cout << "\n解密成功!" << std::endl;
                std::cout << "解密明文: " << plaintext << std::endl;
            } else {
                std::cerr << "\n" << plaintext << std::endl;
            }
        } else {
            std::cerr << "无效选择,请输入 1(加密)、2(解密) 或 0(退出)" << std::endl;
        }
    }

    return 0;
}