凯撒密码算法的实现

发布于:2025-05-01 ⋅ 阅读:(10) ⋅ 点赞:(0)

       在密码学里,凯撒密码(也叫恺撒密码、移位密码、恺撒代码或者恺撒移位)是一种简单且广为人知的加密技术。它属于替换密码的一种,在这种加密方式中,明文中的每个字母都会被替换成字母表中往后移动固定位数的字母。例如,若向左移动 3 位,字母 D 会被替换成 A,E 会变成 B,依此类推。该加密方法以尤利乌斯・恺撒(Julius Caesar)命名,他在私人通信中使用过这种方法。

1. 命名空间结构

namespace ciphers {
    namespace caesar {
        namespace {
            // 辅助函数定义
        }
        // 加密解密主函数定义
    }
}
  • 使用了命名空间 ciphers 和子命名空间 caesar,来组织代码,避免命名冲突

  • 匿名命名空间(namespace {})存放辅助函数,这些辅助函数只能在当前命名空间内访问

2. 辅助函数

inline char get_char(const int x) {
    return char(x + 65);
}

inline int get_value(const char c) {
    return int(c - 65);
}
  • get_char:将0-25的整数值转换为对应的英文字母(A-Z)

  • get_value:将英文字母(A-Z)转换为0-25的整数值

  • 这两个函数通过ASCII码表进行转换(A的ASCII值为65)

3. 加密函数

std::string encrypt(const std::string& text, const int& shift) {
    std::string encrypted_text = "";
    for (char c : text) {
        int place_value = get_value(c);
        place_value = (place_value + shift) % 26;
        char new_char = get_char(place_value);
        encrypted_text += new_char;
    }
    return encrypted_text;
}
  • 遍历输入文本的每个字符

  • 获取字符的整数值,应用凯撒密码公式:(原值 + 移位数) % 26

  • 将加密后的整数值转换为字符,添加到结果字符串

  • 返回加密后的文本

4. 解密函数

std::string decrypt(const std::string& text, const int& shift) {
    std::string decrypted_text = "";
    for (char c : text) {
        int place_value = get_value(c);
        place_value = (place_value - shift) % 26;
        if (place_value < 0) {
            place_value = place_value + 26;
        }
        char new_char = get_char(place_value);
        decrypted_text += new_char;
    }
    return decrypted_text;
}
  • 与加密函数类似,但移位方向相反

  • 添加了对负值的处理,确保解密后的值在0-25范围内

5. 测试函数

void test() {
    // Test 1
    std::string text1 = "ALANTURING";
    std::string encrypted1 = ciphers::caesar::encrypt(text1, 17);
    std::string decrypted1 = ciphers::caesar::decrypt(encrypted1, 17);
    assert(text1 == decrypted1);
    std::cout << "Original text : " << text1;
    std::cout << " , Encrypted text (with shift = 17) : " << encrypted1;
    std::cout << " , Decrypted text : " << decrypted1 << std::endl;

    // Test 2
    std::string text2 = "HELLOWORLD";
    std::string encrypted2 = ciphers::caesar::encrypt(text2, 1729);
    std::string decrypted2 = ciphers::caesar::decrypt(encrypted2, 1729);
    assert(text2 == decrypted2);
    std::cout << "Original text : " << text2;
    std::cout << " , Encrypted text (with shift = 1729) : " << encrypted2;
    std::cout << " , Decrypted text : " << decrypted2 << std::endl;
}
  • 测试了两个不同的输入字符串和移位值

  • 使用 assert 确保加密和解密是互逆过程

  • 打印了原始文本、加密文本和解密文本

6. 主函数

int main() {
    test();
    return 0;
}
  • 调用测试函数运行测试案例

总结

这段代码实现了标准的凯撒密码加密解密功能,具有以下特点:

  1. 使用命名空间组织代码

  2. 提供了辅助函数处理字符和整数之间的转换

  3. 实现了加密和解密的核心逻辑

  4. 包含了测试代码验证功能的正确性

  5. 处理了负值等边界情况

代码结构清晰,功能完整,适合学习和使用凯撒密码的基础实现。