这个程序可以破解来自第六个项目的用凯撒密码加密的信息,即使你不知道密钥。凯撒密码只有 26 个可能的密钥,所以计算机可以很容易地尝试所有可能的解密,并向用户显示结果。在密码学中,我们称这种技术为暴力攻击。如果你想了解更多关于密码和密码破解的知识,你可以阅读我的书《Python 密码破解指南》(NoStarch 出版社,2018)。
当您运行caesarhacker.py时,输出将如下所示:
Caesar Cipher Hacker, by Al Sweigart email@protected
Enter the encrypted Caesar cipher message to hack.
> QIIX QI FC XLI VSWI FYWLIW XSRMKLX.
Key #0: QIIX QI FC XLI VSWI FYWLIW XSRMKLX.
Key #1: PHHW PH EB WKH URVH EXVKHV WRQLJKW.
Key #2: OGGV OG DA VJG TQUG DWUJGU VQPKIJV.
Key #3: NFFU NF CZ UIF SPTF CVTIFT UPOJHIU.
Key #4: MEET ME BY THE ROSE BUSHES TONIGHT.
Key #5: LDDS LD AX SGD QNRD ATRGDR SNMHFGS.
Key #6: KCCR KC ZW RFC PMQC ZSQFCQ RMLGEFR.
`--snip--`请注意,这个程序中的第 20 行到第 36 行与凯撒密码程序中的第 55 行到第 78 行几乎相同。黑客程序实现了相同的解密代码,除了它是在一个for循环中实现的,这个循环为每一个可能的密钥运行代码。
不幸的是,黑客程序不够复杂,无法识别何时找到了正确的密钥。它依赖于人来读取输出,并识别哪个解密产生了原始英语(或任何被加密的书面语言)。《Python 密码破解指南》(NoStarch 出版社,2018)详细介绍了如何编写 Python 代码来检测英文消息。
"""Caesar Cipher Hacker, by Al Sweigart email@protected
This programs hacks messages encrypted with the Caesar cipher by doing
a brute force attack against every possible key.
More info at:
https://en.wikipedia.org/wiki/Caesar_cipher#Breaking_the_cipher
This code is available at https://nostarch.com/big-book-small-python-programming
Tags: tiny, beginner, cryptography, math"""
print('Caesar Cipher Hacker, by Al Sweigart email@protected')
# Let the user specify the message to hack:
print('Enter the encrypted Caesar cipher message to hack.')
message = input('> ')
# Every possible symbol that can be encrypted/decrypted:
# (This must match the SYMBOLS used when encrypting the message.)
SYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for key in range(len(SYMBOLS)): # Loop through every possible key.
translated = ''
# Decrypt each symbol in the message:
for symbol in message:
if symbol in SYMBOLS:
num = SYMBOLS.find(symbol) # Get the number of the symbol.
num = num - key # Decrypt the number.
# Handle the wrap-around if num is less than 0:
if num < 0:
num = num + len(SYMBOLS)
# Add decrypted number's symbol to translated:
translated = translated + SYMBOLS[num]
else:
# Just add the symbol without decrypting:
translated = translated + symbol
# Display the key being tested, along with its decrypted text:
print('Key #{}: {}'.format(key, translated)) 在输入源代码并运行几次之后,尝试对其进行实验性的修改。请记住,存储在SYMBOLS变量中的字符串必须与生成加密文本的凯撒密码程序中的SYMBOLS变量相匹配。
试着找出下列问题的答案。尝试对代码进行一些修改,然后重新运行程序,看看这些修改有什么影响。
- 如果删除或注释掉第 20 行的
translated = '',会得到什么错误信息? - 如果把第 33 行的
translated = translated + SYMBOLS[num]改成translated = translated + symbol会怎么样? - 如果你在凯撒密码黑客程序中输入一条未加密的信息会发生什么?
