加密工具
使用凯撒密码、ROT13和维吉尼亚密码对文本进行加密和解密。
3
常见问题
代码实现
# Caesar Cipher — encode and decode with any shift (ROT13 = shift 13)
def caesar_encode(text: str, shift: int) -> str:
result = []
for ch in text:
if ch.isalpha():
base = ord('A') if ch.isupper() else ord('a')
result.append(chr((ord(ch) - base + shift) % 26 + base))
else:
result.append(ch)
return ''.join(result)
def caesar_decode(text: str, shift: int) -> str:
return caesar_encode(text, -shift)
# ROT13 is simply shift=13
rot13 = lambda s: caesar_encode(s, 13)
print(caesar_encode("Hello, World!", 3)) # Khoor, Zruog!
print(caesar_decode("Khoor, Zruog!", 3)) # Hello, World!
print(rot13("Hello")) # Uryyb
print(rot13("Uryyb")) # Hello (self-inverse)
# Brute-force all 25 shifts to crack a Caesar cipher
ciphertext = "Khoor, Zruog!"
for shift in range(1, 26):
print(f"Shift {shift:2d}: {caesar_decode(ciphertext, shift)}")Comments & Feedback
Comments are powered by Giscus. Sign in with GitHub to leave a comment.