第2周脚本挑战:凯撒密码

发布: (2025年12月26日 GMT+8 04:59)
12 min read
原文: Dev.to

Source: Dev.to

(请提供需要翻译的正文内容,我才能为您完成简体中文翻译。)

第2周安全挑战:凯撒密码

💡 跟着做吗? 所有练习都是开源的! ⭐️ 给 AppSec‑Exercises 仓库 点星,以跟踪我从 Intel Security 到 AppSec Engineer 的 48 周旅程。

“为什么安全工程师需要了解一种已经被破解了2000年的密码?”
因为 Grace Nolan 的安全面试清单 明确把 凯撒密码和基础加密 列为常见的编码挑战。下面说明它为何重要。

为什么在安全面试中会出现凯撒密码?

  1. 测试字符串操作基础
    安全工程师需要解析日志、分析恶意软件、处理网络数据——这些都要求扎实的字符串处理能力。凯撒密码可以测试:

    • 字符遍历
    • ASCII/Unicode 操作
    • 模运算
    • 大小写保持
  2. 揭示密码学理解
    面试官想了解你是否掌握以下概念:

    • 加密 vs. 编码 – 凯撒密码是对称加密(需要密钥)。
    • 密钥空间 – 仅有 26 种可能的密钥 → 极易穷举。
    • 频率分析 – 对替换密码的统计攻击。
    • 现代密码为何存在 – 理解 AES‑256 与之的区别。
  3. 为真实世界安全概念奠基

    • 移位操作 → ROT13、XOR 操作。
    • 对称密钥 → 共享密钥密码学。
    • 密码分析 → 破解弱加密。
    • 深度防御 → 为什么我们不依赖单一加密方式。

挑战

尤利乌斯·凯撒在公元前 58 年用来保护军用信息的凯撒密码,会将字母在字母表中按固定的位数进行移位。

示例

HELLO + shift(3) = KHOOR
XYZ   + shift(3) = ABC   (wrap‑around!)

你的任务是实现此转换,同时保持字母大小写并处理各种边界情况。

你的任务:构建它

第1部分 – 加密

"""
Exercise 3: Caesar Cipher Encoder/Decoder
Week 2 – Python Strings Practice

Inspired by: Python Workout, Second Edition by Reuven M. Lerner
- Chapter 3 (Strings), pages 962‑1200
- Exercise 5 (Pig Latin), demonstrating string transformation

Security Context: Grace Nolan's Security Coding Challenges
Reference: Extended 48‑Week Security Engineering Curriculum, Week 90
"""

def caesar_encrypt(plaintext: str, shift: int) -> str:
    """
    Encrypt text using the Caesar cipher.

    Args:
        plaintext: Text to encrypt.
        shift: Number of positions to shift (can be negative or >26).

    Returns:
        Encrypted ciphertext with original case preserved and
        non‑alphabetic characters left untouched.
    """
    # Your code here
    pass

第2部分 – 解密

def caesar_decrypt(ciphertext: str, shift: int) -> str:
    """
    Decrypt Caesar‑cipher text.

    Args:
        ciphertext: Encrypted text.
        shift: Number of positions used in encryption.

    Returns:
        Decrypted plaintext with original case preserved.
    """
    # Your code here
    pass

要求

  • 保留大小写HelloKhoor(而不是 khoor)。
  • 保留非字母字符Hello, World!Khoor, Zruog!
  • 处理环绕XYZ + 3ABC
  • 支持负移位shift(-3) = 使用 shift(3) 解密。
  • 适用于任意移位 – 包括 shift(26)shift(0)shift(100)

示例测试用例(10 共 95)

# Test 1: Basic encryption
assert caesar_encrypt("HELLO", 3) == "KHOOR"

# Test 2: Wraparound
assert caesar_encrypt("XYZ", 3) == "ABC"

# Test 3: Mixed case preserved
assert caesar_encrypt("Hello, World!", 13) == "Uryyb, Jbeyq!"

# Test 4: Non‑alphabetic preserved
assert caesar_encrypt("test@example.com", 5) == "yjxy@jcfruqj.htr"

# Test 5: Negative shift (decrypt)
assert caesar_encrypt("KHOOR", -3) == "HELLO"

# Test 6: Decryption
assert caesar_decrypt("KHOOR", 3) == "HELLO"

# Test 7: Round‑trip
assert caesar_decrypt(caesar_encrypt("SECURITY", 7), 7) == "SECURITY"

# Test 8: ROT13 (shift 13)
assert caesar_encrypt("HELLO", 13) == "URYYB"

# Test 9: ROT13 property (apply twice = original)
assert caesar_encrypt(caesar_encrypt("Python", 13), 13) == "Python"

# Test 10: Large shift (modulo 26)
assert caesar_encrypt("HELLO", 29) == "KHOOR"   # 29 % 26 = 3

凯撒密码的安全教训

教训 1 – 暴力破解很容易

def brute_force_caesar(ciphertext: str):
    """Try all 26 possible shifts and print the results."""
    for shift in range(26):
        plaintext = caesar_decrypt(ciphertext, shift)
        print(f"Shift {shift}: {plaintext}")

# Example
brute_force_caesar("KHOOR")

现实中的对应: 密码弱且密钥空间很小(例如,4 位 PIN 码只有 10 000 种可能)。

教训 2 – 频率分析可以破解

def frequency_analysis(ciphertext: str) -> int:
    """
    Estimate the shift by assuming the most common letter in English
    ('E') corresponds to the most common letter in the ciphertext.
    """
    freq = {}
    for ch in ciphertext.upper():
        if ch.isalpha():
            freq[ch] = freq.get(ch, 0) + 1

    most_common = max(freq, key=freq.get)
    likely_shift = (ord(most_common) - ord('E')) % 26
    return likely_shift

现实中的对应: 侧信道攻击、计时攻击、流量分析。

教训 3 – 依赖“安全性通过隐蔽”会失败

凯撒密码依赖 移位值 保密。即使不知道移位,也很容易被破解。

现实中的对应:

  • 隐藏 API 端点并不能保证安全。
  • 混淆代码并不能阻止逆向工程。
  • “通过隐蔽获得安全”并不是可靠的防御手段。

什么让现代密码学与众不同?

特性凯撒密码AES‑256
密钥空间26 个可能的密钥2²⁵⁶ 个可能的密钥
抗暴力破解能力微不足道(秒级)在当前技术下几乎不可能
抗频率分析能力无(简单替换)强(混淆与扩散)
使用场景教育/玩具真实世界的数据保护

祝编码愉快,愿你的移位永远正确!

可能的密钥

  • 频率分析

  • 抗已知明文攻击

  • 相同字母 → 相同输出

  • CBC/GCM 模式防止模式出现

  • 几秒内被破解

  • 计算上不可行的破解

Interview Follow‑Up Questions

Be prepared to answer:

Q: “How would you break this cipher without knowing the shift?”
A:

  1. Brute‑force all 26 shifts.
  2. Frequency analysis comparing to English letter frequencies.

Q: “What’s the difference between Caesar cipher and XOR cipher?”
A: Both are symmetric, but XOR uses binary operations and can have variable‑length keys.

Q: “Why do we call ROT13 a special case?”
A: Shift of 13 is self‑inverse: encrypt(encrypt(x)) = x because 13 + 13 = 26 ≡ 0 (mod 26).

Q: “How would you extend this to support Unicode/emoji?”
A: Handle different code‑point ranges or use a lookup table instead of modular arithmetic.

实际应用(历史)

1. ROT13(仍在使用!)

# Hide spoilers on forums, email, Usenet
rot13 = lambda s: caesar_encrypt(s, 13)
print(rot13("Darth Vader is Luke's father"))
# → "Qnegu Inqre vf Yhxr'f sngure"

2. 简单混淆

# Hide config values (NOT secure, just obscured)
api_key = caesar_encrypt("secret_key_12345", 7)

# Decode when needed
real_key = caesar_decrypt(api_key, 7)

警告: 切勿将凯撒密码用于真实的安全场景!

您将练习的 Python 技能

From Python Workout – Chapter 3 (pages 962‑1200):

  • 字符串迭代for char in text
  • 字符检查.isalpha(), .isupper(), .islower()
  • ASCII 转换ord(), chr()
  • 字符串构建 – 连接 vs. 列表拼接
  • 模运算(x + shift) % 26

From Grace Nolan’s Interview Prep:

  • 算法思维 – 位移操作
  • 边缘情况处理 – 空字符串、特殊字符
  • 代码清晰度 – 干净、可读的实现
  • 测试思维 – 全面的测试覆盖

下一步:破解密码学

1. 构建密码分析工具

def crack_caesar(ciphertext):
    """
    Automatically crack Caesar cipher using:
    1. Brute force (try all 26 shifts)
    2. Frequency analysis
    3. Dictionary matching (check if result contains English words)
    """
    pass

2. 扩展到维吉尼亚密码

多字符密钥:HELLO 与密钥 ABCHFNLP

  • 密钥循环:H+A, E+B, L+C, L+A, O+B
  • 比凯撒更安全(但仍可破解!)

3. 与现代密码学比较

实现一个简单的 XOR 密码,然后研究:

  • 为什么使用随机密钥的 XOR(一次性密码本)在理论上是不可破解的。
  • 为什么重复使用密钥会破坏 XOR。
  • AES 与替换密码的区别。

资源

密码学

  • 《The Code Book》 by Simon Singh – 对密码学历史的精彩概述。
  • 《Cryptography Engineering》 by Ferguson, Schneier, Kohno – 现代密码学。
  • Stanford Cryptography I (Coursera) – Dan Boneh 的课程。

Python 字符串操作

  • Python Workout, Second Edition by Reuven M. Lerner – 第 3 章(第 962‑1200 页)。
  • Effective Python by Brett Slatkin – 条目 11:切片序列。

安全面试准备

  • Grace Nolan’s Notes (GitHub: gracenolan/Notes).
  • 《Cracking the Coding Interview》 – 聚焦安全的题目。
  • PortSwigger Web Security Academy – 现代密码学漏洞。

获取完整练习

在 GitHub 上给 AppSec‑Exercises 仓库加星,即可获得全部 95 个测试用例,并跟随我的安全工程之旅!

仓库内容:

  • exercise_03_caesar_cipher.py – 完整练习,包含 95 个测试用例。
  • 我的解答 – 详细实现代码。
  • 与我 48 周课程相匹配的每周安全挑战。
  • LeetCode 风格的格式,完美适用于面试准备。

为什么要加星?

  • 追踪我从 Intel Security → AppSec Engineer 的成长路径。
  • 每周新练习发布时第一时间收到通知。
  • 贡献你的解答和测试用例。
  • 与我一起打造个人作品集。

所有练习均采用 MIT 许可证 – 可自由用于你的面试准备!

我的进度:第 2 周,共 48 周

  • ✅ DNS 基础
  • ✅ TLS/SSL 安全
  • ✅ Python Workout 第 3‑4 章(字符串,列表)
  • ✅ 8 个 PortSwigger SQL 注入实验室
  • 🔄 当前:凯撒密码 + 密码套件分析器
  • 📚 Grace Nolan 的编码挑战:已完成 1/10

目标: 在 2026 年 6 月前转为 AppSec 工程师

在 GitHub 上关注我的旅程 – 每周都有新练习!

大局观

了解为什么凯撒密码会被破解可以教会你:

  • ✅ 认识使密码学安全的因素(密钥空间、抗攻击性)。
  • ✅ 像攻击者一样思考(频率分析、暴力破解)。
  • ✅ 明白为何不要自行实现加密算法(使用经过验证的算法)。
  • ✅ 为现代密码学奠定基础(AES、RSA、椭圆曲线)。

第5周 我们将深入 真实密码学:AES、RSA、使用 bcrypt/Argon2 的密码哈希,以及导致漏洞的常见错误。

现在,通过构建一个有缺陷的系统来掌握基础——随后再学习它为何会出错。

🚀 行动

  • 在 GitHub 上给 AppSec‑Exercises 点星 – 获取每周的安全编码挑战。
  • 💬 留下评论 – 你在面试中见过凯撒密码吗?还有哪些“破碎”的安全概念出现过?
  • 🔔 关注我Dev.toGitHub 上,了解我的完整 48 周旅程。

当前求职: 远程安全工程师职位

标签

Python #Security #Cryptography #Interview #CyberSecurity #AppSec

Back to Blog

相关文章

阅读更多 »

问题 8:统计元音

大家好!👋 今天我们来解决一个字符串操作问题:Counting Vowels。目标是编写一个函数,统计给定字符串中元音的数量……

React 编码挑战:TypeHead

Zeeshan Ali !ZeeshanAli-0704https://media2.dev.to/dynamic/image/width=50,height=50,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws...